Archive
This post is archived and may contain outdated information. It has been set to 'noindex' and should stop showing up in search results.
Beginner AJAX Guide with GET and POST Examples
May 12, 2011ProgrammingComments (5)
AJAX allows you to update parts of a page with server-side content using JavaScript, without reloading the whole page. AJAX is not a new language, but rather a method for using JavaScript to achieve this functionality.

Before diving into AJAX, first take a look at this simple non-AJAX example:

<html>
<head>
<script>
function updateText() {
document.getElementById('content').innerHTML = 'Hello World!';
}
</script>
</head>
<body>
<button onclick="updateText()">Click Me</button>
<div id="content">Nothing here yet.</div>
</body>
</html>

Copy and paste it into an HTML file and run it in your browser. As you can see, with JavaScript you can update parts of a page dynamically, after it has loaded. Practice with this if you aren't familiar with it.

What AJAX does is take this a step further by allowing you to update parts of a page with server-side content (from a database, for example), which could not otherwise be accessed on the client-side after the page has loaded.

You'll need two files to perform AJAX requests. One is your main file that users browse to. I will be using index.php for this example. The other file is never browsed to directly by users; it just performs behind-the-scenes work. I will be using ajax.php for this file. Put both of these files in the same directory on your server.

Here are the contents of these files that I will be using. You can copy and paste it if you'd like. This is an example using the GET method for AJAX (more on that later):

index.php
<html>
<head>
<script>
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (ajax.readyState == 4) {
document.getElementById('content').innerHTML = ajax.responseText;
}
}
function updateText() {
ajax.open('GET', 'ajax.php');
ajax.send();
}
</script>
</head>
<body>
<button onclick="updateText()">Click Me</button>
<div id="content">Nothing here yet.</div>
</body>
</html>

ajax.php
<?php
echo 'Hello world!';

What's happening here is that the XMLHttpRequest object on the index.php page is sending an asynchronous http request to ajax.php, which outputs the text Hello world! that is updated on the original page asynchronously.

The XMLHttpRequest object has an onreadystatechange property that we load an anonymous function into. This function is fired when the request is complete, and the responseText is the text outputted by the ajax.php page.

In this example ajax.php only outputted some static text. But it can do anything you'd normally do server-side, such as accessing a database or the session. If you need to output name and value pairs, arrays, and other information, I recommend using JSON (JavaScript Object Notation).

Here's a bit more information on onreadystatechange: When readyState equals 4, that indicates that the request is complete and the return data (accessed using the responseText property) is available. At that point, you can use JavaScript to do anything you'd like with the data.


Using POST Data


The above example used the GET method. You can also use the POST method, which is good for longer information that needs to be passed. It only requires some minor modifications to the JavaScript (HTML omitted for brevity):

<script>
var ajax = new XMLHttpRequest();
ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
ajax.onreadystatechange = function() {
if (ajax.readyState == 4) {
document.getElementById('content').innerHTML = ajax.responseText;
}
}
function updateText() {
ajax.open('POST', 'ajax.php');
ajax.send('name1=value1&name2=value2');
}
</script>

We set the setRequestHeader property and changed the open type to POST. Then the name and value pairs go directly into the send method.

That's the basics of AJAX. I hope I explained it well enough.



Internet Explorer Quirk


Some versions of Internet Explorer have trouble with AJAX requests and caching the data. You may notice that AJAX requests only work once. This is because IE is caching the return data and just feeding back the same thing after the first request, even if the data changes with each request. You can get around this with the GET method by adding a random name/value pair at the end of your URL (using the Math.random() function for example), or you can just use the POST method, which won't be cached by IE.
Comments (5)
Add a Comment
Creeper Noob Of A Poo 1222111998899   Mar 02, 2018
Because whenever I try to buy it I don't know wich button it is to buy field of dreams
Creeper Noob Of A Poo 1222111998899   Mar 02, 2018
Why can't I get field of dreams on the game
Tony Slark   Jul 04, 2017
it was helped me
Erik Zoltan   Jul 12, 2016
This is a great article. So many articles on this topic use jQuery - which is useful for many people, but not everyone. Your examples show how simple it is to do Ajax in PHP even without jQuery.
Mike Borschow   Sep 29, 2012
Good post. Thanks.