What is jQuery?
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:
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.
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.