top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

jQuery Ajax Introduction

0 votes
256 views

Ajax stands for "Asynchronous JavaScript and XML".

JavaScript includes features of sending asynchronous http request using XMLHttpRequest object. Ajax is about using this ability of JavaScript to send asynchronous http request and get the xml data as a response (also in other formats) and update the part of a web page (using JavaScript) without reloading or refreshing entire web page.

The following figure illustrates the Ajax functionality.

Ajax

The jQuery library includes various methods to send Ajax requests. These methods internally use XMLHttpRequest object of JavaScript. The following table lists all the Ajax methods of jQuery.

jQuery Ajax Methods Description
ajax() Sends asynchronous http request to the server.
get() Sends http GET request to load the data from the server.
Post() Sends http POST request to submit or load the data to the server.
getJSON() Sends http GET request to load JSON encoded data from the server.
getScript() Sends http GET request to load the JavaScript file from the server and then executes it.
load() Sends http request to load the html or text content from the server and add them to DOM element(s).

The jQuery library also includes following events which will be fired based on the state of the Ajax request.

jQuery Ajax Events Description
ajaxComplete() Register a handler function to be called when Ajax requests complete.
ajaxError() Register a handler function to be called when Ajax requests complete with an error.
ajaxSend() Register a handler function to be called before Ajax request is sent.
ajaxStart() Register a handler function to be called when the first Ajax request begins.
ajaxStop() Register a handler function to be called when all the Ajax requests have completed.
ajaxSuccess() Register a handler function to be called when Ajax request completes successfully.

Advantages of jQuery Ajax:

  1. Cross-browser support
  2. Simple methods to use
  3. Ability to send GET and POST requests
  4. Ability to Load JSON, XML, HTML or Scripts

Let's look at an overview of important jQuery Ajax methods in the next section.

posted Feb 6, 2017 by Shivaranjini

  Promote This Article
Facebook Share Button Twitter Share Button LinkedIn Share Button


Related Articles

While using jQuery $.ajax you often need to perform some custom operations upon successful completion of the Ajax request. You may also need to handle errors (if any) that are thrown while issuing the request. To that end jQuery allows you to wire three callback functions as listed below:

  • success callback that gets invoked upon successful completion of an Ajax request
  • failure callback that gets invoked in case there is any error while making the request.
  • completion callback that gets invoked no matter a request completed with or without success.

Additionally, these callback functions can be attached in three distinct ways:

  • Local callbacks : Attaching callback functions as a part of $.ajax() call makes them local to the current Ajax request being made.
  • Global callbacks : Attaching callback functions at global level invokes them for all $.ajax() requests being issued from that page.
  • Promise callbacks : Attaching callback functions to the jqXHR object. This object implements Promise interface.

You can also use one or more of these ways together for an Ajax request.

Let's  quickly see how these three ways can be used. Suppose you you wish to make an Ajax request to a web form - target.aspx. The web form simply returns an HTML markup which is then displayed in a <div> element.

Using local callback functions

To attach local callback functions for success, failure and completion operations you pass them as a part of the settings to $.ajax() method. Consider the following code:

$.ajax({
  url: "target.aspx",
  type: "GET",
  dataType: "html",
  success: function (data, status, jqXHR) {
    $("#container").html(data);
    alert("Local success callback.");
  },
  error: function (jqXHR, status, err) {
    alert("Local error callback.");
  },
  complete: function (jqXHR, status) {
    alert("Local completion callback.");
  }
})

The above code shows various settings being passed to $.ajax() as a JavaScript object. Notice the success, error and complete settings. The success option points to a function that gets invoked upon the successful completion of a request. The success callnack receives three parameters viz. response data, HTTP status and jqXHR ovject. The first two parameters are straightforward. The third parameter is an object that wraps the underlying XMLHttpRequest object and is often referred as jqXHR object.

The error option points to a function that gets invoked in case an Ajax request fails. The error function receives three parameters viz. jqXHR object, HTTP status and exception object that was thrown. In a typical usage you will use the status and err parameters to display an error message to the end user.

The completion option points to a function that gets invoked once the request is complete - no matter whether it completes successfully or with an error. The completion callback receives two parameters viz. jqXHR object and HTTP status.

Using local callback functions is possible the most common approach and has an advantage of simple syntax and usage.

Using global callback functions

You can also wire global success, failure and completion callbacks with Ajax requests. These callbacks are global in that they are invoked for all Ajax requests arising from that page. They don't belong to a specific call. Consider t he following code:

$(document).ajaxSuccess(function (evt, jqXHR, settings) {
  alert("Global success callback.");
});

$(document).ajaxError(function (evt, jqXHR, settings, err) {
  alert("Global error callback.");
});

$(document).ajaxComplete(function (evt, XHR, settings) {
  alert("Global completion callback.");
});

The above code shows three methods of jQuery - ajaxSuccess(), ajaxError() and ajaxComplete() - that are invoked when the respective events happen. These functions are actually Ajax events of jQuery and hence receive an event parameter. Additionally, jqXHR object and settings that were used for making the Ajax request are passed to the event handlers. The error event handler also receives the exception that was throws.

Global callback functions are useful when you wish to perform some common task for all the Ajax requests being issued from the page. They are also useful if you wish to use $.get() and $.post() instead of $.ajax(). Since these methods don't accept error handler as a part of their signature you can't trap errors. Wiring global ajaxError() will provide an error handler for these methods also. 

Using Promise object

A bit modern way to wire these callback functions is to use JavaScript Promise object. A JavaScript Promise is an object that represents a result of an Ajax request (in fact any asynchronous request). The $.ajax() method returns jqXHR object and jqXHR implements the Promise interface. Hence, upon calling $.ajax() you can use done(), fail() and always() methods of the Promise interface to wire the respective callback functions. The following code illustrates how this is done:

var jqXHR = $.ajax({
  url: "target.aspx",
  type: "GET",
  dataType: "html",
}).done(function (data, status, jqXHR) {
  $("#container").html(data);
  alert("Promise success callback.");
}).fail(function (jqXHR,status,err) {
  alert("Promise error callback.");
}).always(function () {
  alert("Promise completion callback.");
})

The above code calls $.ajax() as before however it doesn't provide any local callback functions. The $.ajax() return a jqXHR object and three methods done(), fail() and always() are used to wire callback functions to the respective operations. The function supplied to done() is invoked with the Ajax request completes successfully. The function supplied to fail() is invoked if the request fails. The function supplied to always() is invoked irrespective of whether the request was successful or not. The done() function receives three parameters viz. response data, HTTP status and jqXHR object. The fail() function receives jqXHR object, HTTP status and the error thrown during the request. Finally, the always() function receives the same parameter as that of done() if the request succeeds otherwise it receives the same parameters as that of fail().

READ MORE

While using jQuery $.ajax you often need to perform some custom operations upon successful completion of the Ajax request. You may also need to handle errors (if any) that are thrown while issuing the request. To that end jQuery allows you to wire three callback functions as listed below:

  • success callback that gets invoked upon successful completion of an Ajax request
  • failure callback that gets invoked in case there is any error while making the request.
  • completion callback that gets invoked no matter a request completed with or without success.

Additionally, these callback functions can be attached in three distinct ways:

  • Local callbacks : Attaching callback functions as a part of $.ajax() call makes them local to the current Ajax request being made.
  • Global callbacks : Attaching callback functions at global level invokes them for all $.ajax() requests being issued from that page.
  • Promise callbacks : Attaching callback functions to the jqXHR object. This object implements Promise interface.

You can also use one or more of these ways together for an Ajax request.

Let's  quickly see how these three ways can be used. Suppose you you wish to make an Ajax request to a web form - target.aspx. The web form simply returns an HTML markup which is then displayed in a <div> element.

Using local callback functions

To attach local callback functions for success, failure and completion operations you pass them as a part of the settings to $.ajax() method. Consider the following code:

$.ajax({
  url: "target.aspx",
  type: "GET",
  dataType: "html",
  success: function (data, status, jqXHR) {
    $("#container").html(data);
    alert("Local success callback.");
  },
  error: function (jqXHR, status, err) {
    alert("Local error callback.");
  },
  complete: function (jqXHR, status) {
    alert("Local completion callback.");
  }
})

The above code shows various settings being passed to $.ajax() as a JavaScript object. Notice the success, error and complete settings. The success option points to a function that gets invoked upon the successful completion of a request. The success callnack receives three parameters viz. response data, HTTP status and jqXHR ovject. The first two parameters are straightforward. The third parameter is an object that wraps the underlying XMLHttpRequest object and is often referred as jqXHR object.

The error option points to a function that gets invoked in case an Ajax request fails. The error function receives three parameters viz. jqXHR object, HTTP status and exception object that was thrown. In a typical usage you will use the status and err parameters to display an error message to the end user.

The completion option points to a function that gets invoked once the request is complete - no matter whether it completes successfully or with an error. The completion callback receives two parameters viz. jqXHR object and HTTP status.

Using local callback functions is possible the most common approach and has an advantage of simple syntax and usage.

Using global callback functions

You can also wire global success, failure and completion callbacks with Ajax requests. These callbacks are global in that they are invoked for all Ajax requests arising from that page. They don't belong to a specific call. Consider t he following code:

$(document).ajaxSuccess(function (evt, jqXHR, settings) {
  alert("Global success callback.");
});

$(document).ajaxError(function (evt, jqXHR, settings, err) {
  alert("Global error callback.");
});

$(document).ajaxComplete(function (evt, XHR, settings) {
  alert("Global completion callback.");
});

The above code shows three methods of jQuery - ajaxSuccess(), ajaxError() and ajaxComplete() - that are invoked when the respective events happen. These functions are actually Ajax events of jQuery and hence receive an event parameter. Additionally, jqXHR object and settings that were used for making the Ajax request are passed to the event handlers. The error event handler also receives the exception that was throws.

Global callback functions are useful when you wish to perform some common task for all the Ajax requests being issued from the page. They are also useful if you wish to use $.get() and $.post() instead of $.ajax(). Since these methods don't accept error handler as a part of their signature you can't trap errors. Wiring global ajaxError() will provide an error handler for these methods also. 

Using Promise object

A bit modern way to wire these callback functions is to use JavaScript Promise object. A JavaScript Promise is an object that represents a result of an Ajax request (in fact any asynchronous request). The $.ajax() method returns jqXHR object and jqXHR implements the Promise interface. Hence, upon calling $.ajax() you can use done(), fail() and always() methods of the Promise interface to wire the respective callback functions. The following code illustrates how this is done:

var jqXHR = $.ajax({
  url: "target.aspx",
  type: "GET",
  dataType: "html",
}).done(function (data, status, jqXHR) {
  $("#container").html(data);
  alert("Promise success callback.");
}).fail(function (jqXHR,status,err) {
  alert("Promise error callback.");
}).always(function () {
  alert("Promise completion callback.");
})

The above code calls $.ajax() as before however it doesn't provide any local callback functions. The $.ajax() return a jqXHR object and three methods done(), fail() and always() are used to wire callback functions to the respective operations. The function supplied to done() is invoked with the Ajax request completes successfully. The function supplied to fail() is invoked if the request fails. The function supplied to always() is invoked irrespective of whether the request was successful or not. The done() function receives three parameters viz. response data, HTTP status and jqXHR object. The fail() function receives jqXHR object, HTTP status and the error thrown during the request. Finally, the always() function receives the same parameter as that of done() if the request succeeds otherwise it receives the same parameters as that of fail().

READ MORE

In this article I have taken the example of submitting a contact form consisting of name and address field.

Step 1: Create a New Project.

Go To File -> New -> Select Empty and Checked MVC -> OK



Step 2: Now Right Click on Controllers -> Add -> New Controller -> Name it as HomeController



Step 3: In the HomeController there is Index method create View for it.



Step 4: Now right click on Models -> New -> Class.



In the Contact class write the field which will be on your form. In my form I want only three fields so I have written it as:



Step 5: Go to the Index.cshtml and write the code for form in the body element and don’t give any action to form.



Step 6: Now to submit the form asynchronously we use JQuery. Write the code for it in <script> in the head or you can write it in external file also ,just don’t forgot to give its reference on the page.

In the code we are using the jquery submit event for submitting the form it actually overrides the form submit action. In the $.post(‘url’,serialized form data).success(function(response){//to do}.

The success event get triggers if the data posted successfully. It takes response from the server I am giving alert of the response here.

 

Step 7: Now we have to write controller method to get the form data. Write method in the HomeController I have named it ‘submit’ as I gave in the url. And the submit method takes model contact class as argument which gets filled with the form data; after submitting the form also returns nothing. Give [HttpPost] Annotation to the submit method. Also we are writing in the response that ‘form is submitted successfully’ using Response.writemethod.which gets send to the success event of $.post.



Step 8: Now put breakpoint at your submit method and start debugging your Index.cshtml page. Fill the fields and submit.



After submitting you will find the submitted data in controller method argument and further you will get the alert.



Run

READ MORE
...