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.
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.
<script type="text/javascript">
var http = new XMLHttpRequest();
var data = "username=" + name + '&email=' + email;
http.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// then handle the response
}
}
http.open('ajax.php', 'POST', true);
http.send(data);
</script>
Later, I will explain more about how to handle the response and how to parse it as JSON.
Next, I have created the PHP handler, handler.php to handle the Ajax request. It will look like following.
Haha, it's just a blank file. Jump to the next step!
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.
<?php
include_once $_SERVER['DOCUMENT_ROOT'] . '/inc/autoload.php';
include_once $_SERVER['DOCUMENT_ROOT'] . '/inc/db.php';
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.
header('Content-type: application/json');
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.
<?php
header('Content-type: application/json');
// you can include any script that you need in every ajax handler (optional)
include_once $_SERVER['DOCUMENT_ROOT'] . '/inc/autoload.php';
include_once $_SERVER['DOCUMENT_ROOT'] . '/inc/db.php';
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
<?php
include_once $_SERVER['DOCUMENT_ROOT'] . '/inc/ajax.inc.php';
// ajax.inc.php is the file we created in the last step
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.
<?php
include_once $_SERVER['DOCUMENT_ROOT'] . '/inc/ajax.inc.php';
try {
throw new Exception('Something Went Wrong', 512);
} catch(Exception $e) {
echo json_encode(
array(
'status' => false,
'error' => $e -> getMessage(),
'error_code' => $e -> getCode()
)
);
// do some process if needed. ex: MYSQL Rollbacks
exit;
}
$arr = array(
'status' => false,
'error' => $e -> getMessage(),
'error_code' => $e -> getCode()
);
$arr = json_encode($arr);
echo $arr;
exit;
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 Error
$result = $mysqli -> query("UPDATE users SET username = $username");
if ($result === false) {
throw new Exception('DB Query Failed', 202);
}
2. On Invalid Input
if (empty($_POST['email'])) {
throw new Exception('Invalid Input', 200);
} else {
$email = $_POST['email'];
}
You can use throw statement whenever you need to stop the process and send an error message to the browser.
So, I am going to finish my handler.php. It will throw an error if the request is a GET request.
<?php
include_once $_SERVER['DOCUMENT_ROOT'] . '/inc/ajax.inc.php';
try {
if ($_SERVER['REQUEST_METHOD'] !== "POST") {
throw new Exception('Invalid Request', 2000);
} else {
// status is true if everything is fine
exit(json_encode(
array(
'status' => true
)
));
}
} catch(Exception $e) {
echo json_encode(
array(
'status' => false,
'error' => $e -> getMessage(),
'error_code' => $e -> getCode()
)
);
exit;
}
Let's consider about our JS code again. The final code in index.html will be like following.
<script type="text/javascript">
function jsonParse() {
try {
var json = JSON.parse(text);
}
catch(e) {
return false;
}
return json;
}
var http = new XMLHttpRequest();
var data = "username=" + name + '&email=' + email;
http.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var json = jsonParse(this.responseText);
if (!json || json.status !== true) {
console.log(json.error || 'Something Bad Happened');
return;
}
alert('Everything is Fine!');
}
}
http.open('ajax.php', 'POST', true);
http.send(data);
</script>
Ajax is the best and most popular way to create a dynamic website. It is a must to have knowledge on how to create a PHP handler for Ajax requests, if you are a PHP developer. We have discussed about creating a PHP handler with examples. If you have any question to ask, feel free to comment below.