Welcome to a tutorial and examples of using AJAX with PHP. Yes, the Stone Age of the Internet is long over. If you are still doing “static HTML” or “submit form reload entire page” – It is time to explore the power of AJAX to spice up your website.
AJAX stands for “Asynchronous Javascript And XML”. In simple terms, calling a server-side script without reloading the page. For example, to call a PHP script using AJAX:
fetch("SCRIPT.PHP")
.then(res => res.text())
.then((result) => { console.log(result); });
Yes, AJAX is not as complicated as some people think. Let us walk through a few more examples – Read on!
ⓘ I have included a zip file with all the example code at the end of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.
QUICK SLIDES
TABLE OF CONTENTS
DOWNLOAD & NOTES
Firstly, here is the download link to the example code as promised.
QUICK NOTES
- AJAX will not work with
file://
, usehttp://
.
EXAMPLE CODE DOWNLOAD
Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
PHP AJAX EXAMPLES
All right, let us now get into the examples of using AJAX to call PHP scripts.
EXAMPLE 1) AJAX TO FETCH CONTENTS
<!-- (A) HTML -->
<div id="wrapper"></div>
<!-- (B) JAVASCRIPT -->
<script>
// (B1) AJAX FETCH PHP SCRIPT
fetch("1b-content.php")
// (B2) RETURN SERVER RESPONSE AS TEXT
.then(res => res.text())
// (B3) PUT TEXT INTO WRAPPER
.then((txt) => {
document.getElementById("wrapper").innerHTML = txt;
})
// (B4) OPTIONAL
.catch((err) => { console.error(err); })
.finally(() =>{ console.log("FINALLY"); });
</script>
echo "<strong>This is loaded with AJAX.</strong>";
This is the “full version” of the introduction snippet. Pretty self-explanatory, but for those who are lost:
- (B1)
fetch(URL)
Make an AJAX call to the specified script. DOH. - (B2)
.then(res => res.text())
Then, return the server response as text. Yep, we can also return the results as JSON, binary data, or even a raw data stream. - (B3)
.then((txt) => { ... })
Deal with the fetch results. In this example, we simply put it into<div id="wrapper"></div>
. - (B4)
.catch((err) => { ... })
Optional, deal with errors. - (B5)
.finally(() => { ... })
Optional, this will run regardlessly afterthen()
orcatch()
.
Yep, an AJAX fetch()
works just like a try-catch-finally
block.
P.S. If you do not already know about arrow functions () => {}
, I will do a quick explanation at the bottom.
EXAMPLE 2) AJAX SUBMIT FORM
<!-- (A) HTML FORM -->
<form id="myForm" onsubmit="return ajaxpost()">
<input type="text" name="name" required value="Jon Doe"/>
<input type="email" name="email" required value="jon@doe.com"/>
<input type="submit" value="Go!"/>
</form>
<!-- (B) JAVASCRIPT -->
<script>
function ajaxpost () {
// (B1) GET FORM DATA
var form = document.getElementById("myForm");
var data = new FormData(form);
data.append("KEY", "VALUE"); // ADD MORE DATA IF YOU WANT
// (B2) AJAX POST
fetch("2b-form.php", { method:"POST", body:data })
.then(res => res.text())
// (B3) RESULTS
.then((results) => { console.log(results); });
return false;
}
</script>
print_r($_POST);
What is so cool about using AJAX to submit forms? It will not reload the entire page.
- (A) First, we will use Javascript to handle the form submission
<form onsubmit="return ajaxpost()">
. - (B1) Then collect the form data
- Take note of how we feed the entire HTML form into
var data = new FormData(HTML FORM)
. - Javascript will automatically find all the form fields and adapt the
NAME : VALUE
intovar data
. - If you want to manually add more data, use
data.append(KEY, VALUE)
.
- Take note of how we feed the entire HTML form into
- (B2) Same old
fetch()
and return as text. But take note, we attachdata
andPOST
it to the PHP script. - (B3) Deal with the server response (your server should respond with “OK” or “ERROR”).
EXAMPLE 3) SENDING JSON DATA (ARRAYS & OBJECTS)
// (A) ARRAY DATA
var arr = ["FOO", "BAR"];
var data = new FormData();
data.append("DATA", JSON.stringify(arr));
// (B) SEND TO SERVER
fetch("3b-send-json.php", { method:"POST", body:data })
.then(res => res.text())
.then((results) => { console.log(results); });
$received = json_decode($_POST["DATA"]);
print_r($_POST);
print_r($received);
Sadly, we cannot directly send arrays and objects in AJAX. This is kind of roundabout, but basically –
- (A) Use
JSON.stringify()
to turn an array/object into a JSON encoded string. - (B) POST the JSON encoded string to the server.
- Then in PHP, use
json_decode()
to turn the string back into an array/object.
EXAMPLE 4) RECEIVING JSON DATA
// (A) FETCH FROM SERVER
fetch("4b-fetch-json.php")
// (B) PARSE JSON DATA
.then(res => res.json())
.then((results) => { console.log(results); });
$arr = ["HELLO", "WORLD"];
echo json_encode($arr);
Captain Obvious – We can do the opposite and fetch an array from the server.
EXAMPLE 5) XML HTTP REQUEST
// (A) FORM DATA
var data = new FormData();
data.append("KEY", "VALUE");
// (B) AJAX REQUEST
var xhr = new XMLHttpRequest();
xhr.open("POST", "2b-form.php");
xhr.onload = function () {
console.log(this.status); // HTTP RESPONSE CODE
console.log(this.response); // SERVER RESPONSE TEXT
};
xhr.send(data);
If you have been poking around the Internet, you will notice that some tutorials do AJAX calls differently.
- Yes,
XMLHttpRequest()
is also used to do AJAX. It still works, but this is the “traditional way”. fetch()
is the modern and recommended way.
USEFUL BITS & LINKS
That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.
ARROW FUNCTIONS?
Here’s a quick crash course for the complete newbies.
// (A) YOU ALREADY KNOW THIS
function twice (num) { return num * 2; }
// (B) WE CAN ALSO DO THIS
var twice = function (num) { return num * 2; };
// (C) IN MODERN JS, WE CAN SHORTHAND IT AS AN "ARROW FUNCTION"
var twice = (num) => { return num * 2; };
// (D) FOR A "SINGLE PARAMETER SINGLE RETURN FUNCTION", WE CAN FURTHER SIMPLIFY
var twice = num => num * 2;
COMPATIBILITY CHECKS
- Arrow Functions – CanIUse
- Fetch – CanIUse
Beware if you have to support the ancient browsers – Fallback to the old XMLHttpRequest()
and defining function(){}
.
LINKS & REFERENCES
- XMLHttpRequest – MDN
- FormData – MDN
- Fetch – MDN
- HTTP Status Codes – Wikipedia
- Submit HTML Form Without Refreshing Page – Code Boxx
INFOGRAPHIC CHEAT SHEET

THE END
Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!