Making an AJAX Request to a PHP File

Intro

AJAX stands for Asynchronous JavaScript and XML, and the key to AJAX is the XMLHttpRequest object. From MDN:

XMLHttpRequest is an API that provides client functionality for transferring data between a client and a server. It provides an easy way to retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just a part of the page without disrupting what the user is doing.

Here is a quick tutorial explaining how you can set up this functionality for yourself. If you don’t feel like coding along, you can clone down my GitHub repo. If you’d like to follow along, start by creating a folder. In terminal type mkdir php-xhr .

Install PHP

If you’ve written PHP before, skip to the next section. If not, and you’re a Mac OS X user like myself, simply use the one line installation method as shown here. If you aren’t on a Mac, check out this page for detailed installation instructions on several other platforms. Once you’ve gotten it installed, go ahead and test it out with a simple “Hello World” page. Create a file ending in .php, and copy in the following code. (Notice that PHP code is wrapped in <?php and ?> tags.) Then start a server by typing the following into the command line: php -S localhost:8000. Open localhost:8000 in your browser, and you should see “Hello World” appear. More info on php.net.

<html>
<head>
<title>PHP Test</title>
</head>
<body>
<?php echo '<p>Hello World</p>'; ?>
</body>
</html>

The HTML

Let’s create a file called index.html. It needs to have two components:

  1. a button that will make the XML request
  2. a div to display the content

The code:

// index.html
...
<body>
<button onclick=refreshData()>Say Hello</button>
<div id="content" />
</body>
...

Notice that the button contains an onclick event handler that invokes a function named refreshData. We’ll get back to that shortly.

The PHP

Next, create a file called hello.php.

// hello.php
<?php
print "<p>Hello World</p>";
?>

The JavaScript

Here’s where the magic happens. Back in our index.html file, let’s create that refreshData function. This will execute our XML request.

// index.html
...
<head>
...
<script type="text/javascript">
    function refreshData(){
      var display = document.getElementById("content");
var xmlhttp = new XMLHttpRequest();
      xmlhttp.open("GET", "hello.php");
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send();
      xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
display.innerHTML = this.responseText;
} else {
display.innerHTML = "Loading...";
};
}
}
  </script>
...
</head>
...

Let’s break down what is happening. First, we select our div and set it to a variable called display. Next, we create a new XML HTTP Request, storing it asxmlhttp.

We then initialize XML request with .open(). The first argument is the type of request, and in our case, we are making a “get” request. The second argument is the URL to send the request to; our PHP file. After that, we want to set a request header. This isn’t technically necessary for “get” requests, but we will need it if we want to make a “post” request, and it’s generally good practice. Next, we call .send()to — you guessed it — send the request. (Note that when making a “post” request, .send() can take in data as an argument to send with the request.)

onreadystatechange is an event handler that gets activated any time the “ready state” changes. We set it equal to a function that checks readyState. When that hits 4, we know that the operation has completed. (More info on readyState here.) We also want to make sure we receive a 200 (OK) response. Once we’ve successfully received our response, we want to set our display div equal to the text that we get back. Within our else clause, we set the display div to “Loading…” which will be shown before our request has completed. In our case, the request will happen rapidly, so you may not even see the “Loading” message appear.

Test it out!

In terminal, type php -S localhost:8000 to start a server. Navigate to localhost:8000 in your browser of choice, and our button should appear. Click the button to fire the XML request and if all goes well, “Hello World” will appear under the button.

That’s it! Now you can add AJAX requests to your projects.