5 New jQuery.Ajax() Examples jQuery 1.9+

Sam Deering

Into 2013… And the way we use the jQuery.Ajax() function has changed over recent versions. With this in mind, and older examples being slightly outdated I have coded up 5 New jQuery.ajax() Examples jQuery 1.9+ to show how you might use Ajax with newer versions of jQuery 1.9.x and 2.0.

The new way has some advantages over the old way.

I’ll try keep this post updated with skeleton Ajax snippets for reference. As always comments welcome.

A quick reminder for those learning:

  • The .done() method replaces the deprecated jqXHR.success() method.
  • The .fail() method replaces the deprecated .error() method.
  • The .always() method replaces the deprecated .complete() method.

jQuery 1.9+ Ajax Example 1 – Subscribe to newsletter

This exampe shows a basic Ajax request for subscribing to a newsletter to send name and email to a backend script.

var subscribeRequest = $.ajax({
     type: "POST",
     url: "subscribe.php",
     data: { subscriberName: $('#name').val(), emailAddress: $('#email').val() }
});

subscribeRequest.done(function(msg)
{
     alert( "You have successfully subscribed to our mailing list." );
});

subscribeRequest.fail(function(jqXHR, textStatus)
{
     alert( "We could not subscribe you please try again or contact us if the problem persists (" + textStatus + ")." );
});

jQuery 1.9+ Ajax Example 2 – Request Timeout

This exampe shows how you might catch errors and fails such as timeouts for an ajax request.

Set a timeout (in milliseconds) for the request. The timeout period starts at the point the $.ajax call is made; if several other requests are in progress and the browser has no connections available, it is possible for a request to time out before it can be sent. In Firefox 3.0+ only, script and JSONP requests cannot be cancelled by a timeout; the script will run even if it arrives after the timeout period.

var newDataRequest = $.ajax({
     url: "getNewData.php",
     timeout: 30000, // timeout after 30 seconds
     data: { timestamp: new Date().getTime() }
});

newDataRequest.done(function(data)
{
     console.log(data);
});

newDataRequest.fail(function(jqXHR, textStatus)
{
    if (jqXHR.status === 0)
    {
        alert('Not connect.n Verify Network.');
    }
    else if (jqXHR.status == 404)
    {
        alert('Requested page not found. [404]');
    }
    else if (jqXHR.status == 500)
    {
        alert('Internal Server Error [500].');
    }
    else if (exception === 'parsererror')
    {
        alert('Requested JSON parse failed.');
    }
    else if (exception === 'timeout')
    {
        alert('Time out error.');
    }
    else if (exception === 'abort')
    {
        alert('Ajax request aborted.');
    }
    else
    {
        alert('Uncaught Error.n' + jqXHR.responseText);
    }
});

jQuery 1.9+ Ajax Example 3 – Datafilter

This exampe shows how you can use the dataFilter function to process the raw data which is returned by your Ajax request.

var filterDataRequest = $.ajax({
     url: "getData.php",
     dataFilter: function (data, type)
     {
          //include any conditions to filter data here...
          //some examples below...

          //eg1 - remove all commas from returned data
          return data.replace(",", "");

          //eg2 - if data is json process it in some way
          if (type === 'json')
          {
              var parsed_data = JSON.parse(data);
              $.each(parsed_data, function(i, item)
              {
                  //process the json data
              });
              return JSON.stringify(parsed_data);
          }

     }
});

filterDataRequest.done(function(data)
{
     console.log(data);
});

filterDataRequest.fail(function(jqXHR, textStatus)
{
     console.log( "Ajax request failed... (" + textStatus + ' - ' + jqXHR.responseText ")." );
});

jQuery 1.9+ Ajax Example 4 – MIME Type

This example shows how to specify the content response header types available on a XMLHttpRequest.

If you explicitly pass in a content-type to $.ajax(), then it’ll always be sent to the server (even if no data is sent). If no charset is specified, data will be transmitted to the server using the server’s default charset; you must decode this appropriately on the server side.
var contentTypeRequest = $.ajax({
     url: "getData.php",
     contentType: 'application/x-www-form-urlencoded; charset=UTF-8' //default

     //or choose from one below
     contentType: 'application/atom+xml' //Atom
     contentType: 'text/css' //CSS
     contentType: 'text/javascript' //JavaScript
     contentType: 'image/jpeg' //JPEG Image
     contentType: 'application/json' //JSON
     contentType: 'application/pdf' //PDF
     contentType: 'application/rss+xml; charset=ISO-8859-1' //RSS
     contentType: 'text/plain' //Text (Plain)
     contentType: 'text/xml' //XML
});

contentTypeRequest.done(function(data)
{
     console.log(data);
});

contentTypeRequest.fail(function(jqXHR, textStatus)
{
     console.log( "Ajax request failed... (" + textStatus + ' - ' + jqXHR.responseText ")." );
});


//set specific accept headers (should work cross browser)
$.ajax({
    headers: {
        Accept : "text/plain; charset=utf-8",
        "Content-Type": "text/plain; charset=utf-8"
    }
})

//an alternative to the above
$.ajax({
    beforeSend: function(xhrObj)
    {
        xhrObj.setRequestHeader("Content-Type","application/json");
        xhrObj.setRequestHeader("Accept","application/json");
    }
});

jQuery 1.9+ Ajax Example 5 – Parsing XML

This example i grabbed from the jQuery docs Specifying the data type for ajax requests. It shows loading XML returned from a script and parsing the data as XML (if received by Internet Explorer as plain-text, not text/xml).

By specify the $.ajax dataType option to be “xml”, make sure your server sends content with the “text/xml” MIME type. Sending the wrong MIME type will prohibit jQuery from correctly managing the data returned in the response, and could cause unexpected problems in your script.
var getXMLRequest = $.ajax({
     url: "data.xml.php",
     contentType: "text/xml"
});

getXMLRequest.done(function(data)
{
    console.log(data);
    var xml;
    if (typeof data == "string")
    {
        xml = new ActiveXObject("Microsoft.XMLDOM");
        xml.async = false;
        xml.loadXML(data);
    }
    else
    {
        xml = data;
    }
    // Returned data available in object "xml"
});

getXMLRequest.fail(function(jqXHR, textStatus)
{
     console.log( "Ajax request failed... (" + textStatus + ' - ' + jqXHR.responseText ")." );
});

Win an Annual Membership to Learnable,

SitePoint's Learning Platform

  • http://profiles.google.com/gmilby Greg Milby

    very nice – good work ;-)

  • RITURAJ RATAN

    good work man……

  • Michael Horne

    Seems to me like jQuery is getting changed just for the sake of changing it. Deprecating methods that everyone uses throughout their code is just going to piss them off.

    • http://jquery4u.com/ jQuery4u

      Hi Michael, I agree with some of the changes but some of them are making using jQuery increasing difficult – and migrating from 1.8 to 1.9 to 2.0 is a big one – we need to stay on top of the API. I’ll try my best to post heaps of this stuff on the blog.

  • Ray

    One should note that the behavior of the dataFilter function has changed from 1.8.x to 1.9+.
    In 1.8.x the data parameter was already processed according to the mime type (i.e. an xml document), in 1.9+ it’s always a string.

    • http://jquery4u.com/ jQuery4u

      There isn’t much documentation on this I can find. However in 2.0 it does also check for success before calling dataFilter thus: if ( !prev && isSuccess && s.dataFilter ) { … There was a similar bug opened here: http://bugs.jquery.com/ticket/13613

  • Pingback: 5 New jQuery.Ajax() Examples jQuery 1.9+ | Developer Agent

  • Valentina Alekhine

    Hi. I need to call a php function that returns a XML from my html page (javascript) and I need some help, because I can’t add your code to my page. Please, help me. Thanks a lot :)