5 New jQuery.Ajax() Examples jQuery 1.9+
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.
- 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.
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).
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 ")." );
});