Home / Articles / Programming languages / Scripting languages / JavaScript / jQuery for beginners: AJAX

jQuery for beginners: AJAX

jQuery for beginners: AJAX
 
jQuery for beginners: AJAX
  • Currently 5 out of 5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Rating: 5/5 (2 votes cast)

Thank you for rating!

You have already rated this page, you can only rate it once!

Your rating has been changed, thanks for rating!

Log in or create a user account to rate this page.


In this article I'll try to explain how to implementing AJAX requests.

I think there is no need to explain what AJAX is, because when the web-two-point-oh was introduced most of the users weren't pleased with the re-upload of every page, but when jQuery was introduced the implementation became much easier.

Note: in all the examples, the abbreviated version of the call of jQuery methods is used by using the $ function (dollar sign).

jQuery(..).load

Let's start with the basics - how to load HTML code into the desired DOM element on the page. For this purpose, we will need to use the load method. This method can have the following parameters:

  1. URL of the requested page;
  2. transmitted data (optional);
  3. the function to which the end result will be given for processing (optional).

Here is an example of the JavaScript code:

$( document ).ready(function(){ // after the page download 
  $( '#example-1' ).click(function(){ // putting a click on each element with id = example-1
    $( this ).load( 'ajax/example.html' ); // loading HTML code from the file example.html
  });
});

Example of the loaded data (file content example.html):

Example<br/>
Data Loaded By AJAX<br/>
Bye-Bye

jQuery.ajax

This is the most basic method, and all subsequent methods are like wrappers for the method jQuery.ajax. This method has only one input parameter - an object which includes all the settings (parameters worth remembering):

  • async - asynchronous request, by default - true;
  • cache - on/off browser data caching, by default - true;
  • contentType - by default - "application/x-www-form-urlencoded";
  • data - transmitted data - string or object;
  • dataFilter - filter for the input data;
  • dataType - the type of data returned to the callback function (xml, html, script, json, text, _default);
  • global - trigger - responsible for the use of global AJAX events, by default - true;
  • ifModified - trigger - checks whether there were any changes in the server response, to avoid sending additional request, by default - false;
  • jsonp - reset the name of the callback function to work with JSONP (by default - generated automatically);
  • processData - by default - transmitted data are wrapped in an object, and sent as "application/x-www-form-urlencoded", if otherwise necessary - disable;
  • scriptCharset - coding - important for JSONP and JavaScript load;
  • timeout - timeout in milliseconds;
  • type - GET or POST;
  • url - URL of the requested page.

Local AJAX events:

  • beforeSend - triggered before a request is sent;
  • error - if an error occurred;
  • success - if no errors occurred;
  • complete - triggered after the request.

To organize HTTP authentication:

  • username - log in;
  • password - password.

JavaScript example:

$.ajax({
  url: '/ajax/example.html', // specify the URL and
  dataType : 'json', // type of loaded date
  success: function (data, textStatus) { // putting your handler onto the success function.
    $.each( data, function( i, val ) { // processing the received data
    /* ... */
    });
  }
});

jQuery.get

Loads the page, using for the data transfer the GET request. Can have the following parameters:

  1. URL of the requested page;
  2. transmitted data (optional);
  3. callback function to which the end result will be given for processing (optional);
  4. the type of data returned to the callback function (xml, html, script, json, text, _default).

jQuery.post

This method is similar to the previous one, but the transmitted data will be sent to the server via POST. Can have the following parameters:

  1. URL of the requested page;
  2. transmitted data (optional);
  3. callback function to which the end result will be given for processing (optional);
  4. the type of data returned to the callback function (xml, html, script, json, text, _default).

JavaScript:

$( document ).ready(function(){ // after the page has loaded
  $( '#example-3' ).click(function(){ // putting a click on each element with id = example-3
    $.post( 'ajax/example.xml', {}, function( xml ){ // loading XML from the file example.xml 
      $( '#example-3' ).html( '' );
      $( xml ).find( 'note' ).each(function(){ // filling the DOM element with the XML data
        $( '#example-3' ).append( 'To: ' + $( this ).find( 'to' ).text() + '<br/>' );
        .append( 'From: ' + $( this ).find( 'from' ).text() + '<br/>' );
        .append( '<b>' + $( this ).find( 'heading' ).text() + '</b><br/>' );
        .append( $( this ).find( 'body' ).text() + '<br/>' );
      });
    }, 'xml'); // specifying the date type 
  });
});

File example.xml:

<?xml version="1.0" encoding="UTF-8"?>
<note>
  <to>Tori</to>
  <from>Jan</from>
  <heading>Reminder</heading>
  <body>Don't forget about me this weekend!</body>
</note>

jQuery.getJSON

Loads data in JSON format (more convenient and faster than XML). Can have the following parameters:

  1. URL of the requested page;
  2. transmitted data (optional);
  3. callback function to which the end result will be given for processing (optional).

JavaScript:

$( document ).ready(function(){ // after the page has loaded
  $( '#example-4' ).click(function(){ // putting a click on each element with id = example-4
    $.getJSON( 'ajax/example.json', {}, function( json ){ // loading JSON data from the file example.json 
      $( '#example-4' ).html( '' );
      // filling the DOM element with the data from the JSON object 
      $( '#example-4' ).append( 'To: ' + json.note.to + '<br/>' );
      .append( 'From: ' + json.note.from + '<br/>' );
      .append( '<b>' + json.note.heading + '</b><br/>' );
      .append( json.note.body + '<br/>' );
    }); 
  });
});

File example.json:

{
  note:{
    to: 'Tori',
    from: 'Jan',
    heading: 'Reminder',
    body: 'Don\'t forget about me this weekend!'
  }
}

jQuery.getScript

This function loads and runs the local JavaScript. Can have the following parameters:

  1. URL of the requested page;
  2. transmitted data (optional).

JavaScript:

$( document ).ready(function(){ // after the page has loaded
  $( '#example-5' ).click(function(){ // putting a click on each element with id = example-5
    $.getScript( 'ajax/example.js', function(){ // loading JavaScript from the file example.js
      testAjax(); // run loaded JavaScript
    }); 
  });
});

File example.js:

function testAjax() {
  $( '#example-5' ).html( 'Test completed' ); // changing element with id = example-5
}

Events

For easier development, AJAX requests have couple of events, they can be set for each AJAX request individually or globally. For each event you can place an individual function.

Example of the display of an element with id "loading" while loading any AJAX request:

$( '#loading' ).bind( 'ajaxSend', function(){
  $( this ).show(); // show element
}).bind( 'ajaxComplete', function(){
  $( this ).hide(); // hide element
});

For local events - making changes in the properties of the method ajax:

$.ajax({
  beforeSend: function(){
    // Handle the beforeSend event
  },
  complete: function(){
    // Handle the complete event
  }
  // ...
});

Well now, the list of all event's:

  • ajaxStart - this method is triggered in case when AJAX request has run, and no other requests are present;
  • beforeSend - triggered before the request is sent, allows to edit the XMLHttpRequest. Local event;
  • ajaxSend - triggered before the request is sent, similar to beforeSend;
  • success - triggered after receiving the response if there is no server or data returned error. Local event;
  • ajaxSuccess - triggered after receiving the response, similar to success;
  • error - triggered if an error occurred. Local event;
  • ajaxError - triggered if an error occurred;
  • complete - triggered if the current AJAX request has been processed (with or without an error - always triggered.) Local event;
  • ajaxComplete - global event, similar to complete;
  • ajaxStop - this method is triggered when there are no more active requests.

 

Read also

jQuery for beginners: selectors

jQuery for beginners: selectors

jQuery for JavaScript

jQuery for JavaScript

jQuery UI. Widgets. Dialog (Windows)

jQuery UI. Widgets. Dialog (Windows)

jQuery UI. Widgets. Datepicker (Calendar)

jQuery UI. Widgets. Datepicker (Calendar)

Post comment

basicuse.net
html5_css
106160485398655174790

Quick navigation

General navigation