Very Simple AJAX Examples With PHP (Free Code Download)

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 PHP AJAX Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

  • AJAX will not work with file://, use http://.
If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

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

1a-content.html
<!-- (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>
1b-content.php
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 after then() or catch().

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

2a-form.html
<!-- (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>
2b-form.php
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 into var data.
    • If you want to manually add more data, use data.append(KEY, VALUE).
  • (B2) Same old fetch() and return as text. But take note, we attach data and POST 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)

3a-send-json.html
// (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); });
3a-send-json.php
$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

4a-fetch-json.html
// (A) FETCH FROM SERVER
fetch("4b-fetch-json.php")
 
// (B) PARSE JSON DATA
.then(res => res.json())
.then((results) => { console.log(results); }); 
4b-fetch-json.php
$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

5-xmlhttp.html
// (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

Beware if you have to support the ancient browsers – Fallback to the old XMLHttpRequest() and defining function(){}.

 

LINKS & REFERENCES

 

INFOGRAPHIC CHEAT SHEET

AJAX PHP Example (Click To Enlarge)

 

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!

Leave a Comment

Your email address will not be published.