jQuery for beginners. Part 3. AJAX


    I present to you the third article in the jQuery series for beginners. This time I’ll try to talk about the implementation of AJAX requests ...

    I don’t think what AJAX is, because with the advent of two-zero web, most users already turn their nose to reloading the pages entirely, and with the advent of jQuery, the implementation has become much easier .. .

    Note : In all the examples used a shortened version of the call jQuery methods, using the function $ (dollar sign)

    jQuery (..). load



    Let's start with the simplest thing - loading HTML code into the DOM element we need on the page. For this purpose, the load method is suitable for us. This method can take the following parameters:
    1. url of the requested page
    2. transmitted data (optional parameter)
    3. whose function the result will be fed (optional parameter)

    Let me give you an example of JavaScript code:
    // at the end of the page loading
    $ (document) .ready (function () {              
        // hang on a click on an element with id = example-1
        $ ('# example-1'). click (function () {
            // load HTML code from example.html
            $ (this) .load ('ajax / example.html');       
        }) 
    }); 

    Example of loaded data (contents of example.html file ):
    Example The < br />
    the Data the Loaded By the AJAX < br />
    Bye-Bye


    Work example


    jQuery.ajax


    This is the most basic method, and all subsequent methods are just wrappers for the jQuery.ajax method. This method has only one input parameter - an object that includes all the settings (parameters worth remembering are highlighted):
    • async - request async, defaults to true
    • cache - enable / disable browser caching of data, defaults to true
    • contentType - default is “application / x-www-form-urlencoded”
    • data - transmitted data - string or object
    • dataFilter - filter for input data
    • dataType - data type returned to the callback function (xml, html, script, json, text, _default)
    • global - trigger - responsible for using global AJAX Events, defaults to true
    • ifModified - trigger - checks if there have been changes in the server response, so as not to send another request, the default is false
    • jsonp - reinstall the name of the callback function for working with JSONP (generated by default on the fly)
    • processData - by default, the data sent is wrapped in an object, and sent as "application / x-www-form-urlencoded", if necessary, turn it off
    • scriptCharset - encoding - relevant for JSONP and JavaScript loading
    • timeout - timeout in milliseconds
    • type - GET or POST
    • url - url of the requested page

    Local AJAX Events :
    • beforeSend - fires before sending a request
    • error - if an error occurred
    • success - if no errors have occurred
    • complete - triggered at the end of the request

    To organize HTTP authorization (O_o):
    • username - login
    • password - password

    JavaScript example:
    $ .ajax ({
        url: '/ajax/example.html', // specify URL and
        dataType: "json", // type of loaded data
        success: function (data, textStatus) {// hang our handler on the function success
            $ .each (data, function (i, val) {// process the received data
                / * ... * /
            });
        }
    });



    jQuery.get


    Loads a page using a GET request for data transfer. It can take the following parameters:
    1. url of the requested page
    2. transmitted data (optional parameter)
    3. callback function, which will feed the result (optional parameter)
    4. data type returned to the callback function (xml, html, script, json, text, _default)


    jQuery.post


    This method is similar to the previous one, only the transmitted data will go to the server through POST. It can take the following parameters:
    1. url of the requested page
    2. transmitted data (optional parameter)
    3. callback function, which will feed the result (optional parameter)
    4. data type returned to the callback function (xml, html, script, json, text, _default)


    JavaScript:
    $ (document) .ready (function () {// upon completion of loading the page
        $ ('# example-3'). click (function () {// hang on a click on an element with id = example-3
            $ .post ( 'ajax / example.xml', {}, function (xml) {// load the XML from the example.xml file   
                $ ('# example-3'). html ('');
                $ (xml) .find ('note ') .each (function () {// fill the DOM element with data from XML
                    $ (' # example-3 '). append (' To: '+ $ (this) .find (' to '). text () + '
    ')
                                   .append ('From:' + $ (this) .find ('from'). text () + '
    ')
                                   .append (' '
    + $ (this) .find ('heading'). text () + ' ')
                                   .append ($ (this) .find ('body'). text () + '
    ');
                });
            }, 'xml'); // indicate explicit data type
        })
    });

    Example.xml file :



    Tove
    Jani
    Reminder
    Don't forget me this weekend!


    Work example

    jQuery.getJSON


    Loads data in JSON format (more convenient and faster than XML). It can take the following parameters:
    1. url of the requested page
    2. transmitted data (optional parameter)
    3. callback function, which will feed the result (optional parameter)


    JavaScript:
    $ (document) .ready (function () {// upon completion of loading the page
        $ ('# example-4'). click (function () {// hang on click on the element with id = example-4
            $ .getJSON ( 'ajax / example.json', {}, function (json) {// load JSON data from example.json file   
                $ ('# example-4'). html ('');
                                                             // fill the DOM element with data from JSON object
                $ ('# example-4'). append ('To:' + json.note.to + '
    ')
                               .append ('From:' + json.note.from + '
    ')
                               .append (' ' + json.note.heading + '
    ')
                               .append (json.note.body + '
    ');
            });                
        })
    });

    Example.json file :
    {
        note: {
            to: 'Tove',
            from: 'Jani',
            heading: 'Reminder',
            body: 'Don \' t forget me this weekend! '
        }
    }


    Work example


    jQuery.getScript


    This function loads and executes local JavaScript. It can take the following parameters:
    1. url of requested script
    2. callback function, which will feed the result (optional parameter)


    JavaScript:
    $ (document) .ready (function () {// upon completion of loading the page
        $ ('# example-5'). click (function () {// hang on click on the element with id = example-5
            $ .getScript ( 'ajax / example.js', function () {// load the JavaScript from the file example.js 
                testAjax (); // execute the loaded JavaScript
            });                
        })
    });

    Example.js file :
    function testAjax () {
        $ ('# example-5'). html ('Test completed'); // change the element with id = example-5
    }


    Work example


    Submitting a Form


    You can use any of the above methods to submit the form using jQuery, but for the convenience of "collecting" data from the form, it is better to use the jQuery Form plugin

    Submitting Files


    You can use the Ajax File Upload plugin or One Click Upload to send files using jQuery.

    PHP interaction


    To organize work with PHP I use the jQuery-PHP library , it’s convenient if you like jQuery;), we read in more detail in the article PHP library for jQuery

    JSONP Examples


    Separately, it is worth noting the use of JSONP - because this is one of the ways to implement cross-domain data loading. If you exaggerate a little, it means connecting a remote JavaScript containing the information we need in JSON format, as well as calling our local function, whose name we specify when accessing the remote server (usually this is the callback parameter ). The following diagram can be demonstrated a little more clearly (clickable): When working with jQuery, the name of the callback function is generated automatically for each call to the remote server, for this it is enough to use the GET request of the form:



    http://api.domain.com/?type=jsonp&query=test&callback=?

    Instead of the last question mark (?), The name of the callback function will be substituted. If you do not want to use this method, you will need to explicitly specify the name of the callback function using the jsonp option when calling the jQuery.ajax () method.


    Google search


    An example of obtaining and processing search results using Google, for more information, see the article " jQuery + AJAX + (Google Search API || Yahoo Search API) "

    Yahoo Search


    An example of obtaining and processing search results using Yahoo, more detailed information can be found in the article " jQuery + AJAX + (Google Search API || Yahoo Search API) "

    JSONP API


    I will also give a small list of open APIs with JSONP support:


    Events


    For convenience of development, several events hang on AJAX requests, they can be set for each AJAX request separately, or globally. On all events, you can hang your own function.

    Example for displaying an element with id = "loading" during the execution of any AJAX request:
    $ ("# loading"). bind ("ajaxSend", function () {
        $ (this) .show (); // show the element
    }). bind ("ajaxComplete", function () {
        $ (this) .hide (); // hide the element
    });

    For local events - make changes to the options of the ajax () method:
    $ .ajax ({
        beforeSend: function () {
            // Handle the beforeSend event
        },
        complete: function () {
            // Handle the complete event
        }
        // ...
    });


    For clarity, I’ll give the following diagram (clickable): Well, actually a list of all events:




    • ajaxStart - This method is called when an AJAX request is run, and there are no other requests.
    • beforeSend - Fires before sending a request, allows editing XMLHttpRequest. Local event
    • ajaxSend - Fires before sending a request, similar to beforeSend
    • success - Fires when a response is returned when there are no errors on either the server or the returned data. Local event
    • ajaxSuccess - Fired when a response is returned, similar to success
    • error - Fires in case of an error. Local event
    • ajaxError - Fires on error
    • complete - Triggered upon completion of the current AJAX request (with or without error, it always fires). Local event
    • ajaxComplete - A global event similar to complete
    • ajaxStop - This method is called when there are no more active requests

    You can also download all the examples in one archive .

    Cycle of articles


    1. jQuery for beginners
    2. jQuery for beginners. Part 2. JavaScript Menu
    3. jQuery for beginners. Part 3. AJAX

    PS I used the mini-service http://highlight.hohli.com/ for syntax highlighting

    Also popular now: