Last week we looked at how to use AJAX with plain JavaScript to load data from a server without needing to perform a page refresh, now we’ll look at how to use AJAX with jQuery. Before we get started using AJAX with jQuery, I first want to briefly introduce jQuery.

What is jQuery?

A common misconception about jQuery is that it’s a programming language, the previous is not true, and it is instead a “fast, small, and feature-rich JavaScript library.” In short, jQuery makes writing JavaScript quicker and easier.

For example, instead of using document.getElementById(‘foo’); to get the element with id=’foo’ we could instead use the much simpler jQuery: $(‘#foo’); . The previous example shows how jQuery makes it easier to perform document traversal and manipulation. In addition to the previous, it also makes using AJAX easier.

Ajax and jQuery

jQuery has a wide range of AJAX functions and methods but by far the most versatile is the $.ajax() function. The function signatures for $.ajax() are:

[code lang=”text”]
$.ajax(url,[,options])
$.ajax([options])
[/code]

The url parameter in line 1 is a string containing the URL we want to send the AJAX request to and the options parameter is an object literal containing a set of key/value pairs that will configure our AJAX request. In line 2, the URL would either be included in the options object or omitted if we wanted to make the request to the current page.

The list of $.ajax() can take many different options and the list can be found here . Next, I’ll show an example using some commonly used options.

In the above example when a button on a hypothetical web page is clicked an AJAX GET request will be made for my Github account information. If the request is successful the success function will be run.

Cross-Domain Requests

Before wrapping up I want to discuss briefly why we need to use dataType: ‘jsonp’ in the above code. It is needed because the browser security model requires that any request made be on the same domain. So, if I make the above request from example.com, the request to github.com would be denied since the two domains are different. By using JSONP (JSON with Padding) we can get around the same domain restriction and make the request to github.com. A more detailed explanation of JSONP can be found here.

Conclusion

In this post we looked at how jQuery can be used to make AJAX requests much easier than plain JavaScript. We also saw how we can use JSONP to make cross-domain requests. In our next post we are going to look at how we can use the previous two methods to work with some different web APIs (Application Programming Interfaces). In short, APIs allow us to easily access information from other websites and use them in our own applications. Stop by next week to see the previous in action.