Skip to Main Content
jQuery Cookbook
book

jQuery Cookbook

by Cody Lindley
November 2009
Intermediate to advanced content levelIntermediate to advanced
480 pages
11h 50m
English
O'Reilly Media, Inc.
Content preview from jQuery Cookbook

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

jQuery UI in Action

jQuery UI in Action

TJ VanToll
Head First jQuery

Head First jQuery

Ryan Benedetti, Ronan Cranley

Publisher Resources

ISBN: 9780596806941Supplemental ContentErrata Page