The common use of Ajax in web development has created a dynamic yet fluid Internet. Designers often build mockups which incorporate Ajax-based elements such as lazy loaders, tabbed widgets, and other similar page elements.

In this tutorial I want to delve into a basic example of handling Ajax development with PHP on the backend. Normally you would connect this into a database using an engine like MySQL, but for this tutorial I want to focus on handling the response from PHP, and how you can use this response to append new content onto the page. Take a peek at my live sample demo to get an idea of what we are creating.

Starting with jQuery Ajax

When coding in standard JavaScript we are stuck using a method called XMLHttpRequest. The jQuery Ajax method is a more simplified way of handling this HTTP request, and you have a large index of documentation explaining each of the various options. I’ll be demonstrating two different styles of handling Ajax requests using different return values from PHP.

First I’ve created a new page, index.html, along with a related stylesheet. I won’t go over these codes so if you’re interested just download the project source. I also downloaded a local copy of jQuery along with a blank JavaScript file named ajax.js.

Above I have combined two bits of code from my HTML which are located at different sections in the page. The anchor link using an ID of #followbtn will trigger an event callback when clicked. The same goes for the other anchor link, #morefllwrs. However these events will run different callback functions, and they both expect a different type of request using Ajax.

We can start by looking at the follow button example and how this behavior works.

Simple Ajax Actions

Many social networks like Twitter and Pinterest use Ajax to auto-update the page once you follow a new profile. This would obviously require connecting into a database for any live application, but for this example we can write the PHP as if we already connected into the database. First let’s take a peek at the JS codes.

Once the button is clicked we need to call e.preventDefault to stop the href value from loading a hash symbol into the address bar. Then I’m using .fadeOut() on the button to remove it from the page so that a user doesn’t try clicking twice. You will notice the Ajax request has a lot of different options – certainly not the whole catalog but enough to get us going. I’ll break them down individually so you can understand how the Ajax call works.

url – the external URL to which we are sending the request. In this case I’ve organized all my Ajax PHP scripts into a folder and this one calls ajax-follow.php.

type – the request method, POST or GET.

data – what content are we passing to the PHP file? It should be organized like a JSON string with key:value pairs. So in PHP we can get the ‘action’ value by using $_POST[‘action’].

success – if the Ajax request runs successfully then we either call a separate function or write the callback inline. I usually write the function right within Ajax because it’s often much easier.

error – if the Ajax request fails, or somehow gets an error in the response, this alternative function is triggered. Usually helpful when debugging issues between JS and PHP.

I’ve structured this call so it could work for any simple common action we need to take. The ‘action’ found in our data string could be anything including unfollow, block, send a friend request, etc. The ‘userid’ is just made-up for my example but you’ll need this to be accurate when updating info in a database.

if($_POST['action'] == "follow") {
/**
* we can pass any action like block, follow, unfollow, send PM....
* if we get a 'follow' action then we could take the user ID and create a SQL command
* but with no database, we can simply assume the follow action has been completed and return 'ok'
**/
echo "ok";
}

So now inside ajax-follow.php we can see a very simple block of logic which checks for the action parameter. If we have it set to ‘follow’ then we could run some code that connects into the database and creates a new following relationship from the logged-in user and the current profile. At the end if it all works then we can return any value – I’ve chosen a string ‘ok’.

If you look back in the Ajax code you’ll see we run a logic check for if(data == “ok”). We only want to update the page with a success message if PHP has created the follow relationship. You might also notice we can update the number of followers on the page using a JavaScript method parseInt().

JSON Return Data in PHP

For the second bit of Ajax we want to dynamically load a full list of followers on this user’s profile. We can see this person has 18 followers and only 10 are displaying by default. Each click will load 5 more followers until we have loaded them all. Since we know how Ajax connects into PHP let’s first start with the backend file ajax-followers.php.

PHP uses a special function called header() for setting properties of the page during rendering. In this case we don’t want the data returned as plaintext, but instead using application/json as JSON data. This is formatted in a way that jQuery can easily loop through each follower and then append them into the list.

Notice all I’ve created are simple PHP arrays that contain a profile username and their avatar. There is a $pg1 and $pg2 variable which indicates each of the pages we can load. All of this info could be pulled out of MySQL and would appear in similar syntax using something like mysqli_fetch_assoc().

After both arrays have been defined you’ll see this block of code at the bottom. We check which page is needed by calling upon a variable passed in through jQuery $_POST[‘page’]. Whether it’s page 1 or 2 we just need to json_encode() the array and simply echo it out onto the page(since our document type is application/json). PHP’s exit() is a friendly way of terminating the script when its sole purpose is meant for Ajax calls.

Loading Followers with Ajax

This last bit of code inside ajax.js is much more convoluted than the earlier block. But this is the reason why I wanted to introduce two distinct methods of PHP/Ajax because there is so much to learn about this topic.

Before even getting to the Ajax request let’s delve deeper into the actual event handler. Notice that my selector is targeting the page body and we pass the #morefllwrs button as a parameter to the .on() method. The purpose is to handle clicks on the same link which gets dynamically appended into the page. So right when the DOM loads jQuery will target the first link, and a user will click to load more followers, but in order to get another button to appear we need to add HTML onto the page using jQuery.

This means whenever the user clicks the button a second time, it normally wouldn’t register because it wasn’t part of the original DOM so jQuery doesn’t notice it. By using the whole body as our selector it will keep listening for the click event including new elements which are added to the page after loading. The other code inside just creates variables, and then we replace the button HTML with a loading gif so the user doesn’t click twice.

Much of this syntax will look familiar because we are using the same jQuery function. In this case we need to call a different PHP file and we are passing a page value based on the button’s HREF attribute. It’s just one little trick we can use for dynamically-loaded page results. In fact, the biggest difference will be found inside the success function callback since we are using a type of jQuery .each() loop.

The response from PHP is held in a JS variable called json. We turn each array object inside the JSON string into a new variable called item. Since this is a very basic example the objects only have two keys – item.profile_pic and item.username. Any real-world example might include many more values.

One possibly confusing aspect of this loop is the very first logic check if(typeof item == ‘object’) used on each item. I’m doing this because each JSON response is comprised of profile objects, along with a string at the end called nextpage. When we get to this value we need to handle it differently because it won’t be added into the list, but instead it is used to build the new “Load more followers” button.

If this nextpage value is not ‘end’ then we know it contains some page value like #pg2. We can use this as the new button’s HREF attribute, which gets passed back into PHP to load the next set of followers. Once we hit the last JSON entry then we know there are no more pages. So we don’t append any new button and the loading gif is replaced instead by a single empty paragraph.

Closing

There are hundreds if not thousands of different purposes for creating an Ajax script. You might even connect into 3rd party APIs where you don’t need to host any backend files at all! Web development has advanced so quickly with the rise of open source projects like jQuery. Feel free to download a copy of my demo files and see if you can build any similar interfaces on your own web projects.

23 Responses to “Beginner’s Guide to Ajax Development with PHP”

AJAX provides improved the consumer knowledge with desktop in addition to with mobile phones. Additionally, it has an essential function in abundant world wide web software and a lot of web 2. 0 software including Search engines, askjeeve, Microsoft company, Amazon and others.

Great tutorial, very simple and less code to write. The question or issue I am running into is how to send dynamic php script”$category.php” something like this in url and how to send the parameter to the dynamic php script in the ajax in data “Uniid=$uniid&Uid=$from” any inputs or help would be greatly appreciated.

Ajax requests are triggered by JavaScript code; your code sends a request to a URL, and when it receives a response, a callback function can be triggered to handle the response. Because the request is asynchronous, the rest of your code continues to execute while the request is being processed, so it’s imperative that a callback be used to handle the response.

Traditionally webpages required reloading to update their content. For web-based email this meant that users had to manually reload their inbox to check and see if they had new mail. This had huge drawbacks: it was slow and it required user input. When the user reloaded their inbox, the server had to reconstruct the entire web page and resend all of the HTML, CSS, JavaScript, as well as the user’s email. This was hugely inefficient. Ideally, the server should only have to send the user’s new messages, not the entire page. By 2003, all the major browsers solved this issue by adopting the XMLHttpRequest (XHR) object, allowing browsers to communicate with the server without requiring a page reload.

When my php file returned ok the ajax function would return a error and i could see that the response was there “ok” but it was followed by to arows (enter like symbols) so i have tryed to json_encode my ok response and it worked. I dont know yet why.
I did have the header set for json/app but ???.

Thanks !!
I spent almost 4 hrs and 18 tutorials but none was working. Yours had that small hint i wanted and I am done. Now I can easily upgrade my website with new features like email list. Keep it up.

If it is something I do not understand is why in the success function of the second example(loading followers) the parameter passed instead of data is json.
It is the first time I see such parameter being passed there.

Dimitris, that parameter is just the variable name for the data that is passed back to the success function. You can name it whatever you want. Because json is being passed back from the second PHP script example it’s useful to name the variable ‘json’, rather than just ‘data’.