Chapter 16. jQuery, Ajax, Data Formats: HTML, XML, JSON, JSONP

Jonathan Sharp

Introduction

Web developers work with a number of data formats and protocols in transferring information between browsers and servers. This chapter provides a number of recipes for handling and working with some of the most common data formats, Ajax techniques, and jQuery.

16.1. jQuery and Ajax

Problem

You want to make a request to the server for some additional data without leaving the page the visitor is currently on.

Solution

Here’s a simple Ajax request:

(function($) {
    $(document).ready(function() {
        $('#update').click(function() {
            $.ajax({
                type: 'GET',
                url: 'hello-ajax.html',
                dataType: 'html',
                success: function(html, textStatus) {
                    $('body').append(html);
                },
                error: function(xhr, textStatus, errorThrown) {
                    alert('An error occurred! ' + ( errorThrown ? errorThrown : 
xhr.status );
                }
            });
        });
    });
})(jQuery);

Discussion

At the core of jQuery’s Ajax architecture is the jQuery.ajax() method. This provides the basis of all browsers to server requests and responses. So, let’s look at this in a little more detail. To initiate a request to the server, a settings object that contains parameters for the request is passed to the $.ajax method. A vast number of options are available, with the most common options of a request being type, url, complete, dataType, error, and success:

var options = {
    type: 'GET'
};

The first option that needs to be addressed when starting an Ajax request is the type of HTTP request you’re going to ...

Get jQuery Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.