Pages

Sunday, March 3, 2013

AJAX calls using jQuery


For making ajax call with javascript firstly we need to crate XMLHttpRequest object that is browser dependent then can proceed for ajax call. But jquery has made the things simple as well as with powerful . jQuery provides a rich set of handy methods you can use to Ajaxify your web pages. jQuery provides wrapper methods that shield you from the inner mechanisms of an AJAX request as:

1. GET Request method : jQuery.get( url, [data], [callback], [type] )
2. POST Request method : jQuery.post( url, [data], [callback], [type] )
3. Get JSON : jQuery.getJSON( url, [data], [callback] )
4. AJAX Start/End : jQuery.ajaxStart([callback]), jQuery.ajaxComplete([callback])
5. Serialize html form : serialize(), serializeArray()
6. jQuery.ajax()



1. GET Request method : Loads a remote page using HTTP GET request method. 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).

jQuery.get( 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”.


2. POST Request method : 
Sends HTTP Post request.

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”.


3. Get JSON : 
JavaScript Object Notation (JSON) is a popular light weight format that can be used to get data from server. JSON format is easy to create from the server and easy to parse at client as it is the basic object representation in JavaScript. 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.

jQuery.getJSON( url, [data], [callback] )
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.

4. AJAX Start/End : 

While making a sequence of AJAX requests one being dependent on returned data from other request's response in that case it is good to show a progress bar or image to user so that (s)he knows that something is going on. For such case ajax start/end method 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.

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.

5. Serialize html form :

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.
This value can be sent to server by an AJAX call.

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

6. jQuery.ajax()

If you need greater flexibility, the full-blown $.ajax() function offers a great number of settings.
For instance, let's say you want to retrieve a list of programming languages from the XML document you used in the previous example. You might want to specify the following options:
  1. the request must be an HTTP GET;
  2. the page from which the result is returned must not be in the browser's cache;
  3. the response returned by the server is of data-type XML;
  4. the request is made in html;
  5. there must be a function that handles the returned result if all goes well;
  6. and, finally, there must be a function that handles errors in case the request is not successful.

Tuesday, January 8, 2013

jQuery - AJAX Events

Local Events:

These are callbacks that you can subscribe to within the Ajax
request object.
$.ajax({
   beforeSend: function(){
     // event handling
   },
   complete: function(){
     // event handling
   }
   // ......
 });

Global Events :

These events are broadcast to all elements in the DOM, triggering any
handlers which may be listening. You can listen for these events like so:
$("#loading").bind("ajaxSend", function(){
   $(this).show();
 }).bind("ajaxComplete", function(){
   $(this).hide();
 });
Global events can be disabled, for a particular Ajax request, by
passing in the global option, like so:
 $.ajax({
   url: "MyPage.html",
   global: false,
   // ...
 });

Events:

Below is the full list of Ajax events, where the ajaxStart and ajaxStop events are
 events that relate to all Ajax requests together.
  • ajaxStart (Global Event)
    This event is broadcast if an Ajax request is started and no other
    Ajax requests are currently running.
    • beforeSend (Local Event)
      This event, which is triggered before an Ajax request
      is started, allows you to modify the XMLHttpRequest object
      (setting additional headers, if need be.)
    • ajaxSend (Global Event)
      This global event is also triggered before the request is run.
    • success (Local Event)
      This event is only called if the request was successful (no errors
       from the server, no errors with the data).
    • ajaxSuccess (Global Event)
      This event is also only called if the request was successful.
    • error (Local Event)
      This event is only called if an error occurred with the request
       (you can never have both an error and a success callback with a request).
    • ajaxError (Global Event)
      This global event behaves the same as the local error event.
    • complete (Local Event)
      This event is called regardless of if the request was successful,
      or not. You will always receive a complete callback, even for
      synchronous requests.
    • ajaxComplete (Global Event)
      This event behaves the same as the complete event and will be
      triggered every time an Ajax request finishes.
  • ajaxStop (Global Event)
    This global event is triggered if there are no more Ajax requests being processed.