PHP — AJAX and PHP
AJAX is used to create more interactive applications.
AJAX PHP Example
The following example will demonstrate how a web page can communicate with a web server while a user type characters in an input field:
Example
Start typing a name in the input field below:
Example Explained
In the example above, when a user types a character in the input field, a function called "showHint()" is executed.
The function is triggered by the onkeyup event.
Here is the HTML code:
Example
<html>
<head>
<script>
function showHint(str) <
if (str.length == 0) <
document.getElementById("txtHint").innerHTML = "";
return;
> else <
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() <
if (this.readyState == 4 && this.status == 200) <
document.getElementById("txtHint").innerHTML = this.responseText;
>
>;
xmlhttp.open("GET", "gethint.php?q=" + str, true);
xmlhttp.send();
>
>
</script>
</head>
<body>
First, check if the input field is empty (str.length == 0). If it is, clear the content of the txtHint placeholder and exit the function.
However, if the input field is not empty, do the following:
- Create an XMLHttpRequest object
- Create the function to be executed when the server response is ready
- Send the request off to a PHP file (gethint.php) on the server
- Notice that q parameter is added to the url (gethint.php?q="+str)
- And the str variable holds the content of the input field
The PHP File — "gethint.php"
The PHP file checks an array of names, and returns the corresponding name(s) to the browser:
// get the q parameter from URL
$q = $_REQUEST["q"];
// lookup all hints from array if $q is different from ""
if ($q !== "") <
$q = strtolower($q);
$len=strlen($q);
foreach($a as $name) <
if (stristr($q, substr($name, 0, $len))) <
if ($hint === "") <
$hint = $name;
> else <
$hint .= ", $name";
>
>
>
>
// Output "no suggestion" if no hint was found or output correct values
echo $hint === "" ? "no suggestion" : $hint;
?>
LearnBeginner’s Guide to Ajax Development with PHP
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.
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.
Free trial on Treehouse: Do you want to learn more about Ajax and PHP development? Click here to try a free trial on Treehouse.
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.
Want to learn more about coding, design and more? Try the Treehouse 7-day free trial today!
GET STARTED NOW
Learning with Treehouse for only 30 minutes a day can teach you the skills needed to land the job that you’ve been dreaming about.
How to call a JavaScript function from PHP?
The following code is from xyz.html (on a button click) it calls a wait() in an external xyz.js. This wait() calls wait.php.
where loadxml() calls code from another PHP file the same way.
The loadxml() is working fine otherwise, but it is not being called the way I want it.
![]()
12 Answers 12
As far as PHP is concerned (or really, a web server in general), an HTML page is nothing more complicated than a big string.
All the fancy work you can do with language like PHP — reading from databases and web services and all that — the ultimate end goal is the exact same basic principle: generate a string of HTML*.
Your big HTML string doesn’t become anything more special than that until it’s loaded by a web browser. Once a browser loads the page, then all the other magic happens — layout, box model stuff, DOM generation, and many other things, including JavaScript execution.
So, you don’t «call JavaScript from PHP», you «include a JavaScript function call in your output».
There are many ways to do this, but here are a couple.
Escaping from php mode to direct output mode:
You don’t need to return a function name or anything like that. First of all, stop writing AJAX requests by hand. You’re only making it hard on yourself. Get jQuery or one of the other excellent frameworks out there.
Secondly, understand that you already are going to be executing javascript code once the response is received from the AJAX call.
Here’s an example of what I think you’re doing with jQuery’s AJAX
Now, if you’re dead-set on sending a function name from PHP back to the AJAX call, you can do that too.
AJAX Request Handler with PHP
AJAX is a Web Technology to create asynchronous Web applications. AJAX allows web pages to communicate with the server behind the scenes. The web page can be updated dynamically without reloading.
In this tutorial, we will be discussing about how to write a PHP script to handle an ajax request and send a response back to the client. There are some tasks that handler should do.
- Read input variables correctly
- Handle errors
- Do the process without any error
- Send an appropriate response
Sending the Ajax Request
To perform an Ajax request, some javascript code must be implemented in the web page. But, I do not explain AJAX in Javascript deeply here. I assume that you have a basic knowledge on json too.
First, I’ve created a new page, index.html. I have written JS code in it to send an Ajax request to the server with some data. I have used pure javascript in the following example. If you like, you can use your desired JS library.
Haha, it’s just a blank file. Jump to the next step!
Include Necessary Files
Now, I have included two files that I need in handler.php. First one is the autoload file to autoload class files. (If you are interested, you can follow our autoloading tutorial to learn more). The second one is the database connection file. You can include files according to your needs. I just included these files to show that you can include any php file that you need to execute. So, I won’t be using these files anymore hereafter in this tutorial.
Important!
When Ajax was introduced it was used with XML. But in the present, 99% of developers use JSON because it is lightweight and simple than XML. So, I’ll be working with JSON objects hereafter. There are two PHP functions to use to handle JSON objects: json_encode and json_decode . There’s no problem even you haven’t heard of those functions because it’s easy to understand.
There’s another problem! When the server sends a response in JSON format, server has to tell the browser that the response is in JSON format. So, it’s compulsory to add following code into every PHP script that handles Ajax requests.
However, It isn’t a good idea to add above code in each script. So, including is a great trick. Therefore, I have created ajax.inc.php to save that code as well as to include other files.
Then, I just have to include ajax.inc.php in my Ajax handlers. Let’s focus on handler.php again. It would be like following
Handling Errors
Handling errors is the most important part in the Ajax Handler. There are many ways to implement error handling. But, try-catch model is the best and the most efficient approach according to my personal experience. It’s pretty simple to use. I can send an error message to the client (or the browser) just with throwing an error in PHP after implementing this model. Let’s see how to implement it and response to error PHP catches in runtime.
- First, I have included the files.
- Then, wrapped all the code with a try block
- PHP process goes inside the try block. You can throw a Exception in runtime with a message and an error code. (error code is optional). The catch block will catch any Exception, even it is thrown by a method inside a class.
- I have used throw new Exception statement to throw errors. First parameter is the error message and the second one is the error code
- After catching the thrown error, I have echoed a string that is encoded in JSON which is originally a PHP Array. I have separated the code into parts below to make it easier to understand.
- First, I have created a key-value array which has 3 keys. First two are really important to show an error to the user in the browser and to browser to detect that the Ajax process wasn’t successful. I have set status to false, which will be used later in this tutorial in the front-end (Javascript). $e -> getMessage() returns the string that was defined in the throw statement. It will return an empty string if the string isn’t defined in the statement. Error code is optional to send to the browser, but you can make your application more organized by sending error codes. $e -> getCode returns the error code defined in the throw statement. The default value is 0.
- Next, I have encoded the array in JSON format with json_encode function. That function returns a json encoded string that you don’t need to take care of. PHP makes it easy to encode and it’s really easy to decode it in Javascript too.
- Next, I have echoed the json encoded string.
- Finally, I have exited the script. You can add any code to do some task before you exit the script.
I know it’s a long tutorial, Let’s take a break! I have a question for you. Why do you exit the script just after finding an error on processing? Let me know your opinion by commenting below.
Okay. Next I’ll show you some examples on error handling in Ajax scripts. These are some common places that you might want to throw errors and exit the script.
1. On a Database Query Error2. On Invalid Input
You can use throw statement whenever you need to stop the process and send an error message to the browser.