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

A Guide to UTF-8 for PHP and MySQL

Data Encoding: A Guide to UTF-8 for PHP and MySQL As a MySQL or PHP developer, once you step beyond the comfortable confines of English-only character sets, you quickly find yourself entangled in the wonderfully wacky world of UTF-8. On a previous job, we began running into data encoding issues when displaying bios of artists from all over the world. It soon became apparent that there were problems with the stored data, as sometimes the data was correctly encoded and sometimes it was not. This led programmers to implement a hodge-podge of patches, sometimes with JavaScript, sometimes with HTML charset meta tags, sometimes with PHP, and soon. Soon, we ended up with a list of 600,000 artist bios with double- or triple encoded information, with data being stored in different ways depending on who programmed the feature or implemented the patch. A classical technical rat’s nest.Indeed, navigating through UTF-8 related data encoding issues can be a frustrating and hair-pul...

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]');

Integrating Kafka with Node.js

Integrating Kafka with Node.js Apache Kafka is a popular open-source distributed event streaming platform that uses publish & subscribe mechanism to stream the records(data). Kafka Terminologies Distributed system: Distributed system is a computing environment where various software components located on different machines (over multiple locations). All components coordinate together to get stuff done as one unit.   Kafka Broker: Brokers are cluster of multiple servers. Message of each topic are split among the various brokers. Brokers handle all requests from clients to write and read events. A Kafka cluster is simply a collection of one or more Kafka brokers. Topics: A topic is a stream of "related" messages. Its unique throughout application. Kafka producers write messages to topics. Producer: Producer publishes data on the topics. A producer sends a message to a broker and the broker receives and stores messages. Consumers: Consumers read data from topics. A consu...