jQuery: Making the AJAX coding clutter free

jQuery makes AJAX easier to work with and allows to make AJAX/XMLHttpRequest calls without even worrying about the complicated code flow of XMLHttpRequest

jQuery: Making the AJAX coding clutter free

You must have heard about AJAX. Yes AJAX; Asynchronous Javascript And XML.

But if you have used it; you know how to code to work with AJAX. It is complex and needs everything to be handled exceptionally.

But as a replacement you can use jQuery to make your AJAX code which makes it easier to work with AJAX without even making you worry about the code at client side.

All you have to do is to craft your back-end code for AJAX response.Let take a look at Core JS code to work with AJAX.

var xhr;

if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
  xhr = new XMLHttpRequest();
} else {
// code for IE6, IE5
  xhr = new ActiveXObject("Microsoft.XMLHTTP");
}

xhr.open("GET","getdata.php?name=Pankaj",true);
xhr.send();

xhr.onreadystatechange = function(){
  if ( xhr.readyState==4 && xhr.status==200 ){
    document.getElementById("target").innerHTML=xhr.responseText;
  }
}

In traditional code first you have to think about the browser interoperability; then work on the code to craft GET or POST request; then Send it to server; then wait for response and keep on checking readyState and status to know when the request is completed.

And also the getdata.php file is being called by GET request for data. So code is being made at that script.

Now let's talk about the AJAX done through jQuery.

In jQuery there are many inbuilt functions to handle client side code for AJAX like .ajax(), .get(), .post() etc. For example let's change the above code according to jQuery to do same task.

$.ajax({
  url: "getdata.php?name=Pankaj",
  type: "GET",
  dataType: "html", 
  success: function(data) {
    $("#target").html(data);
  }
});

Here $.ajax() function is used and in above code the GET request was made through AJAX. Now suppose the request is POST and you want to send some attributes through POST. For ex. name=Pankaj

$.ajax({
  url: "getdata.php",
  type: "POST",
  data: { name : "Pankaj" },
  dataType: "html", 
  success: function(data) {
    $("#target").html(data);
  }
});

You Got this! Its very simple to make AJAX request and use the response very effectively!

You can also handle the status and readyStates. Following example you show you how…

var request = $.ajax({
  url: "getdata.php",
  type: "POST",
  data: {name : "Pankaj"},
  dataType: "html"
});

request.done(function(msg) {
  $("#target").html(msg);
});

request.fail(function(jqXHR, textStatus) {
  $("#target").html('Error Occured!'+textStatus);
});

In above code the jqXHR object is same as the xhr object of the core JS code. So you can now use the initial easy code of jQuery and flexible custom response handling. The methods .get() and .post() are known as the shorthand methods.

All shorthand methods are:

$.get()

This function is used to load data from remote source asynchronously via HTTP GET and then perform operations on that loaded data by the callback function.

$.get("getdata.php?name=Pankaj", function(data) {
  $("#target").html(data);
});

$.post()

This function is used to load data from remote source asynchronously via HTTP POST and then perform operations on that loaded data by the callback function.

$.post("getdata.php", {"name" : "Pankaj"}, function(data) {
  $("#target").html(data);
});

$.getJSON()

This function is used to load only JSON data from remote source asynchronously via HTTP GET and then perform operations on that loaded data by the callback function.

//Json File stored on server
{
"name":"Pankaj Patel", 
"website":"http://pankaj.pro", 
"blog":"https://time2hack.blogspot.com"
} 

//Javascript code at client side
$.getJSON( "getdata.json", function(data) {
  $("#target").html(
      data.name + " "
      + data.website + " "
      + data.blog
  );
});

$(…).load()

This function is used to load data from remote source asynchronously via HTTP GET and then replace the loaded content to the target element.

$("button").click(function(){
    $("#target").load("getdata.php", { "name":"Pankaj"}); 
});

There is also a jQuery event handler load and which one is called is completely dependent on the parameters passed.


$.getScript()

This function is used to load and then execute javascript from a remote source asynchronously.

//JavaScript stored at server
alert("This data has been loaded from the server");

//Javascript at the client side
$("#button").click(function(){
    $.getScript("getscript.js"); 
});

Moreover talking on this topic; jQuery provides more settings in .ajax() function to make more customization

It also provides some low level event handlers for AJAX to make the application very robust.

Please share your views about this tutorial.

One more thing I forgot to include; please include the jQuery before practicing your code. Do this by following snippet

Demo Download