Friday, 21 November 2014

Jquery Ajax method

AJAX = Asynchronous JavaScript and XML. AJAX is about loading data in the background and display it on the webpage, without reloading the whole page.
The ajax() method is used to perform an AJAX (asynchronous HTTP) request.

Notes: Asynchronous means that the script will send a request to the server, and continue it's execution without waiting for the reply. As soon as reply is received a browser event is fired, which in turn allows the script to execute associated actions.

The serialize() method creates a URL encoded text string by serializing form values

readyState Holds the status of the XMLHttpRequest. Changes from 0 to 4:

0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready

The parameters specifies:

beforeSend(xhr): A function to run before the request is sent
eg: beforeSend: function() {
    xhr.setRequestHeader("Accept", "text/javascript");
    $('#resp').html('Loading...');
  },

complete(xhr,status):       A function to run when the request is finished (after success and error functions)
eg: complete: function() { alert('complete'); }

contentType:        The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
eg:contentType: "application/json; charset=utf-8",

data:         Specifies data to be sent to the server
eg: data: "id=78&name=some_name"

dataFilter(data,type):      A function used to handle the raw response data of the XMLHttpRequest
eg: dataFilter: function(data) {
    var resp = eval('(' + data + ')');
    return resp;
  },

dataType: The data type expected of the server response.
"xml": Returns a XML document that can be processed via jQuery.
"html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
"script": Evaluates the response as JavaScript and returns it as plain text.
"json": Evaluates the response as JSON and returns a JavaScript object.
"jsonp": Loads in a JSON block using JSONP.
eg: dataType: "script"

error(xhr,status,error): A function to run if the request fails.
            Eg: error: function(xhr, status, error) {
                        var err = eval("(" + xhr.responseText + ")");
                        alert(err.Message);
            }


success(result,status,xhr):           A function to be run when the request succeeds
eg: success: function(response, status, xhr){
    if(status=="success") {
      $("#display").html(response);
    }
    else { alert(status+ ' - '+ xhr.status); }
  }

xhr:           A function used for creating the XMLHttpRequest object

headers :  a map of additional header key/value pairs to send along with the request. This setting is set before the beforeSend function is called; therefore, any values in the headers setting can be overwritten from within the beforeSend function
eg: headers: { "Content-Type": "application/json", "Accept": "application/json" },

statusCode   - a map of numeric HTTP codes and functions to be called when the response has the corresponding code.
eg:
 statusCode: {
    404: function() {
      alert('page not found');
    }

  }
async:   false
you specify the async option to be false to get a synchronous Ajax request. 

Note:At a very basic level, you use an asynchronous mode when you want the call to occur in the background and a synchronous mode when you want your code to wait until the call has completed.
The asynchronous mode is the usual approach for AJAX calls, as you generally attach a callback function to the onreadystatechange event so that you can respond when the server-side data is ready, rather than waiting for the data to arrive.
eg:
var _orgAjax = jQuery.ajaxSettings.xhr;
jQuery.ajaxSettings.xhr = function () {
    var xhr = _orgAjax();
    xhr.onreadystatechange = function() {
        if( xhr.readyState == 4 ) {
             $("div").html("Done");
        }
    }
    return xhr;
};

0 comments:

Post a Comment