Simple AJAX Examples With PHP

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:

  • var xhr = new XMLHttpRequest();
  • xhr.open("POST", "SCRIPT.PHP");
  • xhr.send();

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.

 

 

REAL 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.

 

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.

 

QUICK NOTES

  • AJAX will not work with file://, use http://.

If you spot a bug, please feel free to comment below. I try to answer 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.

 

 

PHP AJAX EXAMPLES

All right, let us now get into the examples of using AJAX to call PHP scripts.

 

1) USING AJAX TO FETCH CONTENTS

1a-content.html
<!-- (A) HTML -->
<div id="wrapper"></div>
 
<!-- (B) JAVASCRIPT -->
<script>
var xhr = new XMLHttpRequest();
xhr.open("GET", "1b-basic.php");
xhr.onload = function () {
  console.log(this.status);
  console.log(this.response);
  document.getElementById("wrapper").innerHTML = this.response;
};
xhr.send();
</script>
1b-content.php
<?php
echo "<strong>This is loaded with AJAX. It works!</strong>";

First, this is kind of a follow-up of the introduction snippet.

  • To make an AJAX request, start by creating a var xhr = new XMLHttpRequest() object.
  • Set the PHP script to call xhr.open("GET", "1b-basic.php").
  • Use xhr.onload = function () { ... } to do something when the server responds.
    • this.status contains the HTTP response code, this is usually 200 when nothing goes wrong. Other “common bad codes” can be the infamous 404 not found, and 403 unauthorized. I will leave a link to the full list in the extras section below.
    • this.response contains whatever text the server responded with. In this example, we simply set the server response into <div id="wrapper">.
  • Lastly, we launch the AJAX request with xhr.send().

 

 

2) AJAX SUBMIT FORM

2a-post.html
<!-- (A) HTML FORM -->
<form onsubmit="return ajaxpost()">
  <input type="text" id="name" required value="Jon Doe"/>
  <input type="email" id="email" required value="jon@doe.com"/>
  <input type="submit" value="Go!"/>
</form>
<div id="response"></div>
 
<!-- (B) JAVASCRIPT -->
<script>
function ajaxpost () {
  // (B1) FORM DATA
  var data = new FormData();
  data.append("name", document.getElementById("name").value);
  data.append("email", document.getElementById("email").value);
 
  // (B2) AJAX POST
  var xhr = new XMLHttpRequest();
  xhr.open("POST", "2b-post.php");
  xhr.onload = function () {
    document.getElementById("response").innerHTML = this.response;
  };
  xhr.send(data);
  return false;
}
</script>
2b-post.php
<?php
print_r($_POST);

Using the “traditional” <form action="SCRIPT.PHP"> form submission is cool, but it reloads the entire page. Just how do we submit a form without reloading the page? AJAX is the answer.

  • First, we will use Javascript to handle the form submission instead <form onsubmit="return ajaxpost()">.
  • Then collect the form data – var data = new FormData() and data.append("KEY", "VALUE").
  • Lastly, submit the form using AJAX. This is the same XMLHttpRequest object, but take note that we are sending the data along in this AJAX request – xhr.send(data).

 

 

3) HANDLING ARRAYS & OBJECTS

3a-array.html
<!-- (A) HTML FORM -->
<input type="button" value="Go!" onclick="doajax()"/>
<div id="response"></div>
 
<!-- (B) JAVASCRIPT -->
<script>
function doajax () {
  // (B1) DUMMY DATA
  var arr = ["FOO", "BAR"];
  arr = JSON.stringify(arr); // ARRAY TO STRING
  var obj = {hello : "world"};
  obj = JSON.stringify(obj); // OBJECT TO STRING
 
  // (B2) FORM DATA
  var data = new FormData();
  data.append("ARR", arr);
  data.append("OBJ", obj);
 
  // (B3) AJAX POST
  var xhr = new XMLHttpRequest();
  xhr.open("POST", "3b-array.php");
  xhr.onload = function () {
    var res = JSON.parse(this.response);
    console.log(this.response); // STRING
    console.log(res); // OBJECT
  };
  xhr.send(data);
  return false;
}
</script>
3b-array.php
<?php
$arr = [
  "ARR" => json_decode($_POST['ARR']),
  "OBJ" => json_decode($_POST['OBJ'])
];
echo json_encode($arr);

Sadly, we cannot directly send arrays and objects in AJAX. This is kind of long-winded, but basically –

  • Use JSON encode to turn an array/object into a string.
  • POST the JSON encoded string.
  • Then, use JSON decode to turn the string back into an array/object.

 

 

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.

 

INFOGRAPHIC CHEAT SHEET

AJAX PHP Example (Click To Enlarge)

 

LINKS & REFERENCES

 

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. Required fields are marked *