What Is AJAX?
Let’s look at an example to understand how you could use AJAX in your day-to-day application development. Say you want to build a page that displays a user’s profile information, with different sections like personal information, social information, notifications, messages, and so on.
The usual approach would be to build different web pages for each section. So for example, users would click the social information link to reload the browser and display a page with the social information. This makes it slower to navigate between sections, though, since the user has to wait for the browser to reload and the page to render again each time.
On the other hand, you could also use AJAX to build an interface that loads all the information without refreshing the page. In this case, you can display different tabs for all sections, and by clicking on the tab it fetches the corresponding content from the back-end server and updates the page without refreshing the browser. This helps you to improve the overall end-user experience.
The overall AJAX call works something like this:
Let’s quickly go through the usual AJAX flow:
- First, the user opens a web page as usual with a synchronous request.
- Next, the user clicks on a DOM element—usually a button or link—that initiates an asynchronous request to the back-end server. The end user won’t notice this since the call is made asynchronously and doesn’t refresh the browser. However, you can spot these AJAX calls using a tool like Firebug.
- In response to the AJAX request, the server may return XML, JSON, or HTML string data.
- Finally, the parsed data is updated in the web page’s DOM.
So as you can see, the web page is updated with real-time data from the server without the browser reloading.
Let’s go through the above code to understand what’s happening behind the scenes.
- First, we initialize the
XMLHttpRequestobject, which is responsible for making AJAX calls.
XMLHttpRequestobject has a
readyStateproperty, and the value of that property changes during the request lifecycle. It can hold one of four values:
- We can set up a listener function for state changes using the
onreadystatechangeproperty. And that’s what we’ve done in the above example: we’ve used a function which will be called every time the state property is changed.
- In that function, we’ve checked if the
4, which means the request is completed and we’ve got a response from the server. Next, we’ve checked if the status code equals
200, which means the request was successful. Finally, we fetch the response which is stored in the
responseTextproperty of the
- After setting up the listener, we initiate the request by calling the
openmethod of the
readyStateproperty value will be set to 1 after this call.
- Finally, we’ve called the
sendmethod of the
XMLHttpRequestobject, which actually sends the request to the server. The
readyStateproperty value will be set to 2 after this call.
- When the server responds, it will eventually set the
readyStatevalue to 4, and you should see an alert box displaying the response from the server.
In the next section, we’ll see how to use the
Promise object for AJAX.
Promise is an object which may have one of the three states: pending, resolved, or rejected. Initially, the
Promise object is in the pending state, but as the asynchronous operation is completed, it may evaluate to the resolved or rejected state.
Let’s quickly revise the previous example with the
AjaxCallWithPromise function is called, it returns the promise object, and it’s in the pending state initially. Based on the response, it’ll call either the
Next, we use the
then method, which is used to schedule callbacks when the promise object is successfully resolved. The
then method takes two arguments. The first argument is a callback which will be executed when the promise is resolved, and the second argument is a callback for the rejected state.
How AJAX Works Using the jQuery Library
The jQuery library provides a few different methods to perform AJAX calls, although here we’ll look at the standard
ajax method, which is the most often used.
Take a look at the following example.
As you already know, the
$ sign is used to refer to a jQuery object.
The first parameter of the
ajax method is the URL that will be called in the background to fetch content from the server side. The second parameter is in JSON format and lets you specify values for some different options supported by the
In most cases, you will need to specify the success and error callbacks. The success callback will be called after the successful completion of the AJAX call. The response returned by the server will be passed along to the success callback. On the other hand, the failure callback will be called if something goes wrong and there was an issue performing the AJAX call.
In the next section, we’ll see a real-world example to understand how this all works with PHP.
A Real-World AJAX Example With PHP
In this section, we’ll build an example that fetches JSON content from a PHP file on the server side using AJAX.
For demonstration purposes, we’ll build an example which performs user login using AJAX and jQuery. To start with, let’s make the index.php file, as shown in the following snippet, which renders a basic login form.
We’ve used the
submit event of the form element, which will be triggered when a user clicks on the submit button. In that event handler, we’ve initiated the AJAX call, which submits the form data to the login.php file using the POST method asynchronously. Once we receive a response from the server, we parse it using the
parse method of the
JSON object. And finally, based on the success or failure, we take the appropriate action.
Let’s also see what login.php looks like.
The login.php file contains the logic of authenticating users and returns a JSON response based on the success or failure of login.
Using Promises for AJAX With jQuery
Apart from this, the
always that you could use in the context of Promises.
Let’s quickly revise the jQuery snippet which we’ve used in our example to show how to use it with the
In this tutorial, we discussed the basics of AJAX and how it works with a PHP app. In the first half of the article, we looked at how AJAX works in vanilla JS and in the jQuery library. In the latter half, we built a real-world example which demonstrated how you can use AJAX to fetch server-side PHP content
Learn PHP With a Free Online Course
If you want to learn PHP, check out our free online course on PHP fundamentals!
In this course, you’ll learn the fundamentals of PHP programming. You’ll start with the basics, learning how PHP works and writing simple PHP loops and functions. Then you’ll build up to coding classes for simple object-oriented programming (OOP). Along the way, you’ll learn all the most important skills for writing apps for the web: you’ll get a chance to practice responding to GET and POST requests, parsing JSON, authenticating users, and using a MySQL database.