Chapter 4. AJAX
One of jQuery’s most used features is its suite of AJAX functions. They offer some significant improvements over the native JavaScript AJAX features, as they are a lot easier to use. AJAX is the act of making an HTTP request from JavaScript without having to reload the page; you could think of it as an inline HTTP request. Sometimes, however, it isn’t worth loading the entire jQuery library to send a few requests and nothing else, or it doesn’t provide enough control. It’s also useful to know how jQuery does it, as it can help you when you’re trying to debug your code. jQuery’s $.ajax function is also a massive 379 lines long at the time of writing.
In this chapter, we will cover the basics of AJAX, explore a bit about designing a website to use AJAX, and then AJAXify an example piece of code. This chapter contains a bit of PHP, but PHP knowledge isn’t strictly necessary—it’s not complicated PHP and I will be explaining it along the way.
Sending an AJAX Request
To send an AJAX request in jQuery, we use this very simple syntax:
$.get('/ajax/?foo=bar',function(data){console.log(data);// The response});
Sending an AJAX request in JavaScript alone is a lot more complicated. To send an AJAX request, we use the XMLHttpRequest object (or ActiveXObject in older versions of Internet Explorer). Here is an example of a basic AJAX request:
if(window.XMLHttpRequest){varreq=newXMLHttpRequest();}else{// Internet Explorervarreq=newActiveXObject('Microsoft.XMLHTTP' ...
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.
Read now
Unlock full access