Sunday, April 24, 2011

Easy Ajax Development with jQuery

Categories:


What’s Ajax?
AJAX is a short hand for Asynchronous JavaScript and XML. Ajax is a technique for handling external data through JavaScript asynchronously, without reloading the entire page. It means that instead of waiting for the whole page to load, you can load only what you need to. So if you only need to update one small text part of your site, you don’t have to worry about loading everything else on that page. Probably some of the best example of ajax handy applications are Google Suggest, Google Map, facebook and GMail e.t.c . XMLHttpRequest Object is the heart of the ajax. You can write your own plain javascript code to make an ajax call to the server using  XMLHttpRequest object. But In this article, we are going to discus how to get started with AJAX using the jQuery JavaScript framework?
What’s jQuery?
jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript.  jQuery’s methodology is simple: find things, do stuff. We select elements from the document (via the DOM) using the jQuery function, aliased as $(). This handy function acts just like document.getElementById(), except that instead of only supporting IDs, it supports CSS selectors and some XPath selectors; and, instead of returning one element, it can return an array of elements. XPath selectors are known as the XML Path Language, which is used for finding and manipulating elements in xml documents. Its similar to how you would select some elements in CSS.  You can find more details on jQuery at http://docs.jquery.com/Main_Page. The jQuery library has a full suite of AJAX capabilities. Let us have a look on them.

Getting Started :

jQuery provides some powerful set of  API’s to handle AJAX requests. The normal way of making AJAX calls using JavaScript is a bit odd as you have to first create an XMLHttpRequest object which is dependent on the browser and then make an AJAX call. Also sending a form data using AJAX is also bit difficult if we use normal JavaScript approach of calling AJAX. jQuery provides simple yet powerfull functions which have extended the JavaScript AJAX methods and provide more flexible way. Let us see different ways of doing AJAX things in jQuery.

Ajax request using GET  method:
Load a remote page using HTTP GET request method. This is an easy way to send a simple GET request to a server. It allows a single callback function to be specified that will be executed when the request is complete (and only if the response has a successful response code).

Syntax -

jQuery.get( url, [ data ], [ callback], [ dataType ] )
url: (String) The URL of the page to load.
data (Optional): (Map) Key/value pairs that will be sent to the server.
callback (Optional): (Function) A function to be executed whenever the data is loaded successfully.
type (Optional): (String) Type of data to be returned to callback function: “xml”, “html”, “script”, “json”, “jsonp”, or “text”.
Example -
//Gets the test.jsp page content, store it in a XMLHttpResponse object and show it in a alert box.
$.get(
     "test.jsp",
     "{key:value}",
     function(data){
          alert(data); 
     },
     "html"
);
Ajax request using POST  method:
Load data from the server using HTTP POST request method. This is an easy way to send a simple POST request to a server.

Syntax -

jQuery.post( url, [data], [callback], [type] )
url: (String) The URL of the page to load.
data (Optional): (Map) Key/value pairs that will be sent to the server.
callback (Optional): (Function) A function to be executed whenever the data is loaded successfully.
type (Optional): (String) Type of data to be returned to callback function: “xml”, “html”, “script”, “json”, “jsonp”, or “text”.

Example -
//Gets the test.php page content, store it in a XMLHttpResponse object and applies to the process() JavaScript function.
$.post(
     "test.jsp",
     { name: "John", time: "2pm" },
     function(data) {
           process(data);
     },
     "xml"
);

Ajax equest using JSON  format:
JavaScript Object Notation (JSON) is a popular light weight format that can be used to get data from server. JSON has became very popular since that web pages have became interactive using AJAX. JSON format is easy to create from the server and easy to parse at client as it is the basic object representation in JavaScript.
JQuery provides a function that can be used to make an AJAX call and get the data in JSON format. Normally the data that we get from AJAX is converted in JSON by calling eval () method of JavaScript. But the function provided by JQuery handles this internally and provides direct JSON object as output.
Syntax -
jQuery.getJSON( url, [data], [callback] ) 

Example -
//Loads the four most recent cat pictures from the Flickr JSONP API
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
  {
    tags: "cat",
    tagmode: "any",
    format: "json"
  },
  function(data) {
     $.each(data.items, function(i,item){
          $("").attr("src", item.media.m).appendTo("#images");
          if ( i == 3 ) return false;
  });
});

ajaxStart() and ajaxComplete() methods:
While you make an AJAX call and get some data from server, it is good to show a progress bar or image to user so that (s)he knows that something is going on. Hence Loading… text is common in AJAX enabled application.
What if you web application is making many AJAX calls like gmail. You may want to display a Loading… text while any of AJAX call is proceeding. To achieve this ajaxStart() and ajaxComplete() methods of jQuery can be used.
ajaxStart() method registers a function handler that will be called by jQuery internally whenever an AJAX call is made. If already a request is active than the handler is not called. We can use this method to register a handler function that will display our progress bar.

$.ajaxStart(function() {
     $("div#loading").text("Loading...");
});

In above code snippet, we used ajaxStart() method to register a function that set the innerHTML of div to Loading…
Similarly ajaxComplete() method can be used to register a handler function which gets called by jQuery when an AJAX request get completed and any other active request are not in progress.

$.ajaxComplete(function() {
     $("div#loading").text("");
});

serialize() and serializeArray()  methods:
While submitting a form using AJAX, one has to create a input string that contains the value of all the input elements on the screen. It is very difficult to create this string if your form is very big. Hence we can use jQuery’s serialize() and serializeArray() method to do so.

Serialize() Serializes a set of input elements into a string of data. Serialize is typically used to prepare user input data to be posted to a server. The serialized data is in a standard format that is compatible with almost all server side programming languages and frameworks. In order to work properly serialize requires that form fields have a name attribute. Having only an id will not work.


var str = $("form").serialize();
$("#results").text(str);

In above code snippet, we created a serialize output of the form. This value can be sent to server by an AJAX call.

SerializeArray() serializeArray() does the similar job. Except it creates JSON output.

[
     {name: 'firstname', value: 'Hello'},
     {name: 'lastname', value: 'World'},
     {name: 'alias'}, // this one was empty
]

ajaxSuccess() and ajaxError() methods-
Whenever an Ajax request completes successfully, jQuery triggers the ajaxSuccess event. Any and all handlers that have been registered with the .ajaxSuccess() method are executed at this time.
$('div.log').ajaxSuccess(function() {
      $(this).text('Triggered ajaxSuccess handler.');
});

In the above code, when Ajax request completes successfully, the log message is displayed.
Similarly whenever an Ajax request completes with an error, jQuery triggers the ajaxError event. Any and all handlers that have been registered with the .ajaxError() method are executed at this time.
$("#msg").ajaxError(function(event, request, settings){
         $(this).append("Error requesting page " + settings.url + "");
});

When the  Ajax request fails, the error message is displayed. 


Spread The Love, Share Our Article

Related Posts

No Response to "Easy Ajax Development with jQuery"

Post a Comment