Skip to content
jeff1evesque edited this page Jan 3, 2015 · 15 revisions

##Overview

Asynchronous Javascript, and XML (i.e. AJAX), is an approach that allows client-side code to interact with server-side logic, without changing the layout and design of webpage (i.e. reloading the page).

Though, the X in AJAX generally stands for XML, JSON is most often preferred. JSON has the advantage of being both lighter, and an existing component of javascript.

###AJAX Parameters

An AJAX process is defined simplistically as follows:

$.ajax( url [, settings] )

The following are parameters to the above$.ajax() instance:

  • url: (required) URL where the request is sent
  • type: type of request to make (defaults to GET)
  • data: data to be sent to the action script defined by url
  • dataType: type of data expected back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response.
  • beforeSend, a callback executed before the request is sent.

###Deferred Methods

The following callback handlers execute when their deferred objects resolve:

  • [deferred].done( function(data) { ... } ): replaces the deprecated jqXHR.success() method

    • data: an optional parameter representing the response data from the server-side
  • deferred.fail( function(jqXHR, textStatus, errorThrown) { ... } ): replaces the deprecated jqXHR.error() method

    • jqXHR: string describing the type of error that occurred and an optional exception object, if one occurred
    • textStatus: possible values for this argument are timeout, error, abort, and parsererror
    • errorThrown: textual portion of the HTTP status

Note: in context of the upcoming examples, the deferred objects are the AJAX processes.

###Example #1

This is an example of an ajax process, that submits form field values, to an action script. This script, is predefined by the AJAX url attribute. In this case, the value corresponds to the action attribute defined within the HTML form.

$(document).ready(function() {
  $('form').on('submit', function(event) {
    event.preventDefault();

  // Serialize Form
    var data_formatted = $('form').serializeArray();

  // AJAX Request
    $.ajax({
      url: $(this).attr('action'),
      type: 'POST',
      data : data_formatted,
      dataType : 'json',
      beforeSend: function() {

    // Add AJAX overlay, and Form Validation
      [...]

      }
    }).done(function(data) {

  // Server Response
      [...]

  // Remove AJAX overlay
      [...]

    }).fail(function(jqXHR, textStatus, errorThrown) {

  // Error Message
      [...]

    });

  });
});

###Example #2

This is an example of an ajax process, that submits form file-upload(s), to an action script predefined by the AJAX url attribute. Specifically, an array input elements with attribute, name="svm_dataset[]", is appended to the FormData() object. This object is submitted to a fixed action script.

$(document).ready(function() {
  $('form').on('submit', function(event) {
    event.preventDefault();

  // local variables
    var form_data = new FormData();
    var dataset   = $('input[name="svm_dataset[]"]');
    var flag_ajax = true;

  // store 'file upload(s)' in array
    if ( dataset.length > 0 && dataset.attr('type') == 'file' ) {
      $( dataset ).each(function( index ) {
        var file_data = dataset[index].files[0];
        form_data.append('file_upload_' + index, file_data);
      });
    }

  // undefined 'file upload(s)' sets 'flag_ajax = false'
    dataset.each(function() {
      if ( typeof $(this).val() === 'undefined' ) {
        flag_ajax = false;
        return false
      }
    });

  // ajax request: 'svm_dataset[]' file upload(s)
    if ( flag_ajax ) {
      $.ajax({
        url: '../../php/load_dataset.php',
        type: 'POST',
        data: form_data,
        dataType: 'json',
        contentType: false,
        processData: false,
      }).done(function(data) {

  // Server Response
      [...]

      }).fail(function(jqXHR, textStatus, errorThrown) {

  // Error Message
      [...]

      });
    }

  });
});

Clone this wiki locally