AJAX capabilities of JQuery

In previous article, we discussed about Implementing Effects & DOM manipulation functions. In this article, we will cover AJAX capabilities of JQuery. We can load data from the server without page refresh using AJAX functions. The major functions under this category are: $.get(), $.post() and $.ajax(). $.get() loads data from the server using HTTP GET request.

Its syntax:

$.get( url, [ data ], [ callback(data, textStatus, XMLHttpRequest) ], [ dataType ] )

Here,

  • 1st parameter: URL to which request need to be sent.
  • 2nd parameter: data that need to be sent to server along with request.
  • 3rd parameter: function that need to be called if request succeeds.
  • 4th parameter: Type of data returned from the server like xml, html...

Let's see an example using ASP.NET MVC 2. Create a new MVC 2 web application and name it as JQueryGetSample. ASP.NET MVC supports JQuery within it. So, no need to add script files. Visual Studio 2008 provides intellisense for JQuery using vsdoc file present under scripts folder as shown below:

  

Now, add below code to site.master under head section:

<script type="text/javascript">

        $(function() { $.get('account/getdata', { firstName: "AAA", lastName: "BBB" }, function(data) { alert("From Server: "+ data); }) });

</script>

Here, we are calling getdata method present in AccountController and showing the result returned as an alert. Data is passed to method in JSON format. MVC routing engine will take care of redirecting the request to AccountController. We add below method to AccountController.cs, which can be called over HTTP GET:

[HttpGet]

public string GetData(string firstName,string lastName)

{

    return "Hello "+firstName+", "+lastName;

}

We can return back text, html or xml from the GetData() method.  

Now, We look into $.getJSON() to return JSON object from the server using HTTP GET request. Its syntax:

$.getJSON( url, [ data ], [ callback(data, textStatus) ] )

Here,

  • 1st parameter: URL to which request need to be sent.
  • 2nd parameter: data that need to be sent to server along with request.
  • 3rd parameter: Callback function to be called on success.

Change your GetData() to below:

[HttpGet]

public JsonResult GetData(string firstName,string lastName)

{

    var name = new { fullName = (firstName + lastName) };

    return Json(name, JsonRequestBehavior.AllowGet);

}

Similarly change the code for calling GetData() to shown below:

<script type="text/javascript">

      $(function() { $.getJSON('account/getdata', { firstname: "AAA", lastname: "BBB" }, function(data) { alert(data.fullName); }); });

</script>

By this way, we can return JSON encoded object from the server. In the similar way, we can use $.getScript() to load .js file from server using GET HTTP request and execute it. 

$.load() will helps us to load data from server and place the returned HTML into specified element. It works on both GET and POST requests. If you pass data as an object in load(), it will use POST else GET. I am going to use same JQueryGetSample solution in this article also. It syntax:

 

.load( url, [ data ], [ complete(responseText, textStatus, XMLHttpRequest) ] )

 

Here,

  • 1st parameter: URL to which request need to be sent.
  • 2nd parameter: data that need to be sent to server along with request.
  • 3rd parameter: function that need to be called if request completes.

I added a sample HTML page called myLoad.htm to the solution and called load() as shown below:

<script type="text/javascript">

      $(function() {

           $('#title').load("../../myLoad.htm", null, function() {

alert("Completed");

      });

      });

</script>

This will load myLoad.htm into title div tag. This .load() function is similar to .get() , except that .load() on success will set the HTML contents to the returned result for matching elements. 

 

Now, we will look into serialize(). Serialize() will help us to create a JSON format for HTML form elements having name property for those. We can create a string with this format:

 

Control-name1:value1& Control-name2:value2......

<script type="text/javascript">

        $(function() {

            alert($('form').serialize());

        });

</script> 

The above script will serialize all form elements like textbox, textarea etc having name property and shows them in JSON format.

 

We can use .parseJSON() to get a javascript object from well formed JSON string a shown below:

<script type="text/javascript">

        $(function() {

  var myObj = $.parseJSON('{"name":"test","id":"123","sal":"4500"}');

            alert(myObj.name + "," + myObj.id + "," + myObj.sal);

        });

</script>

We will move over to post(). $.post() loads data from the server using HTTP POST request. Its syntax:

 

$.post( url, [ data ], [ success(data, textStatus, XMLHttpRequest) ], [ dataType ] )

 

Here,

  • 1st parameter: URL to which request need to be sent.
  • 2nd parameter: data that need to be sent to server along with request.
  • 3rd parameter: function that need to be called if request succeeds.
  • 4th parameter: Type of data returned from the server.

Pages fetched using post() will not be cached. I added getdata() to account controller as shown below:

[HttpPost]

public JsonResult GetData(string firstName,string lastName)

{

    var name = new { fullName = (firstName + lastName) };

    return Json(name);

}

And called it using $.post() as shown below with datatype expected as json:

<script type="text/javascript">

        $(function() {

$.post('account/getdata', { firstname: "AAA", lastname: "BBB" }, function(data) { alert(data.fullName);

},"json");

});

</script>

 

The other overloaded functions for $.post() are:

  • $.post('test.aspx') : Requests the page and ignores the result.
  • $.post('test.aspx', {name: test, id: 1234}) : Requests the page along with sending some data in JSON format.
  • $.post('test.aspx',null,function(){//callback..},"xml") : Requests the page and callback on success and data type expected as xm

we will cover $.ajax() and its supporting functions. I used below script, that will explain the Ajax functions.

<script type="text/javascript">

        $(function() {

            $.ajaxSetup({ url: 'account/getdata' });// Specify default values for all AJAX requests.

            $('#title').ajaxStart(function() { $(this).html('<div>Ajax Call started.</div>'); });//Called on Ajax Call

            $('#title').ajaxComplete(function(event, request, settings) { $('<div>Ajax Call Completed.</div>').appendTo($(this)); });// Called on Ajax call completes

            $('#title').ajaxStop(function() { $('<div>Ajax Call Stopped.</div>').appendTo($(this)); });//Called when no pending AJAX requests

            $('#title').ajaxSuccess(function() { $('<div>Ajax Call Succeed.</div>').appendTo($(this)); });//Called When Request is succeed

            $('#title').ajaxError(function(e, xhr, settings, exception) { $('<div>Ajax Call Completed.</div>').appendTo($(this)); });//Called when Error occurs like invalid url...

            $.ajax({

                type: "POST",

                data: { firstname: "test", lastname: "123" },

                success: function(data) {

                var s = '<div>Loaded ' + data.fullName + '.</div>'; $(s).appendTo($('#title'));

                }

            }); // Makes a AJAX called

            $.ajax({

                type: "POST",

                data: { firstname: "test", lastname: "1234" },

                success: function(data) {

                    var s = '<div>Loaded ' + data.fullName + '.</div>'; $(s).appendTo($('#title'));

                }

            }); // Makes a Another AJAX called

        });

</script>

ajaxSetup() : This function is used to specify default values to AJAX requests. In above script, the default value of url is given. If any ajax request is missing the url property, than it will be taken from that function as a default value.

ajaxStart() : This function is used to register a handler to be called on first AJAX request.

ajaxComplete(): This function is used to register a handler to be called on AJAX request completion. 

ajaxStop(): This function is used to register a handler to be called , when there is no pending AJAX requests.

In above functions, we can give selector or JQuery object as anyone. Similarly, ajaxError() and ajaxSuccess() will be called on success/error of the AJAX request. We will finish this section with ajax(). This function is core for all ajax functions. It's all parameters are optional. It's syntax:

$.ajax(url:' ', data:'', success:function(){}, dataType:'', type:'GET or POST', timeout:in ms.... )

ajax() can handle data types like xml, html, json and text. By default, AJAX requests are made using HTTP GET method.

For complete list of parameters of $.ajax(), refer https://api.jquery.com/jQuery.ajax/ .

In above script, I am making an ajax call over POST and displaying the data after success. We can write callbacks for ajax request beforeSend, error, success and complete events. 

We can use ajax() in place of get() function with below syntax:

$.ajax({

  url: url,

  data: data,

  success: success,

  dataType: dataType

});

In the same way, post() functionality can be achieved using:

      $.ajax({

      type: 'POST',

      url: url,

     data: data,

     success: success

     dataType: dataType

     });

We can use .ajaxSend() function to register a handler to be called before sending Ajax request. It's syntax:

ajaxSend( handler(event, XMLHttpRequest, ajaxOptions) )

Example:

$('#title').ajaxSend(function(e, xr, settings) {alert(settings.url);});

For list of AJAX functions, refer https://api.jquery.com/category/ajax/.