Welcome to a tutorial and examples of using AJAX with PHP. The Stone Age of the Internet is long over. If you are still doing “static HTML” or “submit a form and reload the 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(txt => { /* TXT IS OUTPUT FROM SCRIPT.PHP */ });
Yes, AJAX is not as complicated as some people think. Let us walk through a few more examples – Read on!
TABLE OF CONTENTS
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
EXAMPLE CODE DOWNLOAD
Just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
SORRY FOR THE ADS...
But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.
Buy Me A Coffee Code Boxx eBooks
PHP AJAX EXAMPLES
All right, let us now get into the examples of using AJAX to call PHP scripts.
TUTORIAL VIDEO
EXAMPLE 1) AJAX TO FETCH CONTENTS
<!-- (A) HTML WRAPPER -->
<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>
<?php
// (C) HTML CONTENT
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. - (B2)
.then(res => res.text())
Return the server response as plain 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">
. - (B4)
.catch(err => ...)
Optional, deal with errors. - (B4)
.finally(() => ...)
Optional, this will run regardlessly afterthen()
orcatch()
.
If you think this looks familiar, you are right. 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"),
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(txt => {
console.log(txt);
// do something with txt
});
return false;
}
</script>
<?php
// (C) ECHO SUBMITTED FORM DATA
print_r($_POST);
What is so cool about using AJAX to submit forms? It will not reload the entire page.
- (A) Use Javascript to handle the form submission
<form onsubmit="return ajaxpost()">
. - (B1) Collect the form data
- We feed the entire HTML form into
var data = new FormData(FORM)
. This will automatically adapt the form fieldsNAME : VALUE
intodata
. - If you want to add more data, use
data.append(KEY, VALUE)
.
- We feed the entire HTML form into
- (B2) Same old
fetch()
, but we POST the data to the server –{ method:"POST", body:data }
- (C) Do your own processing in your project, then respond with “OK” or “ERROR”.
- (B3) Deal with the results. Take note, we
return false
to prevent the default form submission and reloading the page.
P.S. For GET requests, simply append a query string behind the URL – SCRIPT.PHP?KEY=VALUE&KEY=VALUE
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(txt => console.log(txt));
<?php
// (C) JSON DECODE BACK INTO ARRAY
$received = json_decode($_POST["DATA"]);
print_r($_POST);
print_r($received);
To send arrays and objects in AJAX, a common way is to JSON encode-decode it:
- Use
JSON.stringify()
to turn an array/object into a JSON encoded string. - 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) FETCHING JSON DATA
<?php
// (A) OUTPUT JSON ENCODED STRING
$arr = ["HELLO", "WORLD"];
echo json_encode($arr);
// (B) FETCH FROM SERVER
fetch("4a-fetch-json.php")
// (C) PARSE JSON DATA
.then(res => res.json())
.then(data => { console.log(data); });
- The PHP server-side will output a JSON encoded array –
json_encode($ARRAY)
. fetch(SCRIPT.PHP)
Get data from the server.- JSON decode it back into an array –
.then(res => res.json())
.
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.
EXTRAS
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) WE CAN FURTHER SIMPLIFY "SINGLE PARAMETER & RETURN" FUNCTIONS
var twice = num => num * 2;
// (E) RUN!
console.log(twice(123));
CONSOLE LOG?
For the absolute beginners once again.
console.log()
will output a message to the developer’s console.- In most modern browsers, press
F12 > console
to open it. - This is a very useful tool for debugging, Javascript will also output any error messages here as well.
- Don’t skip on basics – Follow up with Very simple Javascript debugging. A 10-minute tutorial will definitely save you from a lot of pain in the future.
COMPATIBILITY CHECKS
- Arrow Functions – CanIUse
- Fetch – CanIUse
Beware if you have to support ancient browsers. Fallback to use XMLHttpRequest()
and define functions in the “old school way” – function(){}
.
LINKS & REFERENCES
- XMLHttpRequest – MDN
- FormData – MDN
- Fetch – MDN
- HTTP Status Codes – Wikipedia
- Submit HTML Form Without Refreshing Page – Code Boxx
- Cross-Origin Fetch In Javascript – Code Boxx
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!
Thanks
First example works. Could not get the rest to work. The style is clean and entertaining, thank you
Thanks for the feedback – Just press F12 to open the developer’s console… Tutorial updated, added “Console Log” to the “extras” section.
Do you honestly have to be condescending every two sentences..? People who land on your site, clearly don’t know everything and seek explanations. That can also be done without all the “Yep”, “It’s that simple”, “DOH”-horsesh*t.
https://code-boxx.com/faq/#nolike
https://code-boxx.com/faq/#experttroll
How much brain damage must one suffer to get offended by simple YEP and DOH? 😆
P.S. Voicing aggression and egocentric opinions when you should be giving thanks? Good luck with that toxic behavior, I won’t be the one getting hurt anyway. Go fix your sanity and attitude. You are horsesh*t pathetic as it stands.