Skip to main content

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;
};

Comments

Popular posts from this blog

Generate XML file in Cakephp

Steps to Generate XML file using CakePHP: Step-1 Enable to parse xml extension in config route.php file.     Router::parseExtensions('xml'); Step-2 Add Request Handler Component to the Controller    var $components = array(‘RequestHandler’); Step-3 Add controller Action For XML Generation in Post Controller     function generateXMLFile()     {         if ($this->RequestHandler->isXml()) { // check request type             $this->layout = 'empty'; // create an empty layout in app/views/layouts/empty.ctp              }        }  Add header code in empty layout <?php header('Content-type: text/xml');?> <?php echo $this->Xml->header(); ?> <?php echo $content_for_layout; ?> Step-4 Set up View To generate XML Create xml folder inside Posts vi...

Simple JavaScript Object and Class Examples

In JavaScript, most things are objects. An object is a collection of related data and/or functionality Namespace: Everything you create in JavaScript is by default global. In JavaScript namespace is Global object . How to create a namespace in JavaScript? Create one global object, and all variables, methods, and functions become properties of that object. Example:  // global namespace var MYAPP = MYAPP || {}; Explaination: Here we first checked whether MYAPP is already defined.If yes, then use the existing MYAPP global object, otherwise create an empty object called MYAPP How to create sub namespaces? // sub namespace MYAPP.event = {}; Class JavaScript is a prototype-based language and contains no class statement.JavaScript classes create simple objects and deal with inheritance. Example: var Person = function () {}; Explaination: Here we define a new class called Person with an empty constructor. Use the class keyword class Calculation {}; A class expr...

How To Create Shortcodes In WordPress

We can create own shortcode by using its predified hooks add_shortcode( 'hello-world', 'techsudhir_hello_world_shortcode' ); 1. Write the Shortcode Function Write a function with a unique name, which will execute the code you’d like the shortcode to trigger: function techsudhir_hello_world_shortcode() {    return 'Hello world!'; } Example: [hello-world] If we were to use this function normally, it would return Hello world! as a string 2. Shortcode function with parameters function techsudhir_hello_world_shortcode( $atts ) {    $a = shortcode_atts( array(       'name' => 'world'    ), $atts );    return 'Hello ' . $a['name'] . !'; } Example: [hello-world name="Sudhir"] You can also call shortcode function in PHP using do_shortcode function Example: do_shortcode('[hello-world]');