jQuery Ajax Introduction

As we already know, AJAX is a technique to update parts of a web page without reloading the entire web page. Ajax stands for Asynchronous JavaScript and Xml. jQuery supports AJAX functionality through various methods. Using jQuery AJAX methods we can request text, HTML, XML or JSON content from the server. We can send HTTP Get and HTTP Post requests using jQuery AJAX methods and also display the external data in the web page by loading the external data into the selected HTML elements.

also read:

If you are looking for a good book on jQuery, please buy jQuery in Action

We can have AJAX functionality without using the jQuery but we’ll have to handle browser compatibility issues on our own because each browser has different AJAX syntax and implementation. jQuery eliminates this problem by providing unified AJAX methods. This is one of the greatest advantages of using the frameworks which handles the problems of providing the browser compatibility, etc.

load() Method

The load() method loads data from remote server and puts the loaded data into the selected HTML element of the page. This method has three parameters, the following table summarizes the parameters.

URLThe URL of the data to load.
data(Optional) request parameters. These are key/value   pairs we can send along with URL as part of the query string.
callback(Optional) function to execute after the load()   method completes execution. We specify the name of the function to execute.

The following code snippet loads the content from welcome.html file and displays it into the myDiv.

$(document).ready(function(){
  $("#myDiv").load("welcome.html");
});

We can also have optional callback method to execute after the load method executes successfully. The following code snippet loads the content from welcome.html just like above example and also has a callback function defined.

$(document).ready(function(){
  $("#myDiv").load("welcome.html", function(response,statusCode, requestObj){
    alert(response + '  ' + statusCode + '  ' + requestObj);
  });
});

Notice that the callback function in the above example has three parameters which represent the response from the load method call if load method call is succeeded, the status code of the call and XMLHTTPRequest object respectively. The sample run of the above code gives us the following output as shown in the screen capture.

ajax-callback

We can find out whether the call is successful by checking the parameter statusCode. For successful call the statusCode will be success whereas for failed call the statusCode will be error.

In case of error we can use requestObj.status and requestObj.statusText to find out the status of the failed request and reason for failure. The following is the sample code and output of a sample run with an invalid URL to load.

$(document).ready(function(){
  $("#myDiv").load("welcomeNotFound.html", function(response,statusCode, requestObj){
    alert(statusCode + '  ' + requestObj.status + '  ' + requestObj.statusText);
  });
});

ajax-callback-invalid

Thus we can have alternate functionality in case the requested URL is failed to load.

$.get() Method

The $.get() method sends a HTTP Get request to the specified URL and gets response back. The following snippet of jQuery code sends a GET request to the page welcome.html and prints the data and status using the alert box.

$(document).ready(function(){
    $("#btn").click(function(){
        $.get("welcome.html",function(data,status){
          alert("Data: " + data + "\nStatus: " + status);
        });
    });
});

We can also send some data along with the request optionally as shown below:

$.get("welcome.php", { username:"Some User", usertype:"Subscribed User" });

The following example also sends the GET request with some data and processes the response returned from the server.

$(document).ready(function(){
    $("#btn").click(function(){
        $.get("welcome.php",{username: "Some User", usertype: "Subscribed User"},
         function(data, status){
          alert("Data: " + data + "\nStatus: " + status);
        });
    });
});

$.post() Method

The $.POST sends a HTTP Post request and gets response back from the server. The following snippet of jQuery code sends a POST request and appends the result to the div myDiv.

    $("#btn").click(function() {
      $.post("post_data.php", {dataToPost: "myData"},function(result){
        $("#myDiv").html(result);
      });
    });

Optionally, we can also specify dataType when sending a POST request. The dataType indicates the type of the data expected from the server response. jQuery will do a guess if we do not specify the dataType. The possible types are html, xml, JSON and text etc.

I hope this article would have provided the very basis idea on using the jQuery Ajax in your project. In my next posts I will write about various examples using the jQuery Ajax. If you want to receive the mail updates, please subscribe here.

also read:

If you are looking for a good book on jQuery, please buy jQuery in Action

Comments

comments

About Ganesh Prakhya

Trackbacks

  1. […] the jQuery Ajax Introduction, we discussed about sending Ajax requests and processing returned data using jQuery. In this […]

  2. […] our previous articles, we discussed about how jQuery AJAX works and also various jQuery global AJAX event handlers available in jQuery. In this article, […]

Speak Your Mind

*