Beginner AJAX Guide with GET and POST Examples (PHP, JavaScript)
Posted May 12, 2011 by Nick Vogt in Programming
In a nutshell, 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, it's just a method for using JavaScript to achieve this functionality.

To use AJAX you will need to know a bit of JavaScript and (for this example) PHP, and have a server that can parse PHP. If you don't have this, you can download Apache server and PHP for free from their respective websites (follow my guide on setting up Apache, MySQL, and PHP on Windows).

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

<html>
<head>
<script type="text/javascript">
function hello()
{
   document.getElementById('content').innerHTML = 'Hello World!';
}
</script>
</head>
<body>

<input type="button" value="Click Me" onclick="hello();">

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

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 type="text/javascript">
if(window.ActiveXObject) var ajax = new ActiveXObject('Microsoft.XMLHTTP');
else var ajax = new XMLHttpRequest();

function hello()
{
   ajax.open('GET', 'ajax.php', true);
   ajax.onreadystatechange = function()
   {
      if(ajax.readyState == 4)
      {
         document.getElementById('content').innerHTML = ajax.responseText;
      }
   }
   ajax.send(null);
}
</script>
</head>
<body>

<input type="button" value="Click Me" onclick="hello();">

<div id="content">Nothing here yet.</div>

</body>
</html>

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

If you create the above files and run them in your server, it should perform essentially the same thing that the first code section did, except it does it very differently.

When the page is first loaded, a variable "ajax" is created, which is a JavaScript object that contains the AJAX methods. You'll notice that we use a conditional statement to create this object. You guessed it, browser compatibility. Older versions of Internet Explorer use ActiveXObject, while modern browsers such as Firefox and Chrome use XMLHttpRequest.

When the function "hello" is called, it uses the open method of the ajax object, which tells it what type of request it will be (in this case, GET), the URL to the file, and whether it is asynchronous or not (true for asynchronous). Then it sets up the function that fires when the onreadystatechange method of the AJAX object changes, which handles the response data. Finally, it uses the send method to send the request.

Once the request is sent, that's where ajax.php comes into play. Anything that is written to the document (in this case, just 'Hello World!') will comprise the response text that gets returned to index.php. You can access a database in the ajax.php file, check the user's cookies, and do just about anything else you'd normally do with PHP. If you need to return name and value pairs, arrays, and other information back to JavaScript, I recommend using JSON (JavaScript Object Notation).

Here's a bit more information on the onreadystatechange function. When readyState equals 4, that indicates that the request is complete and the return data (accessed using the responseText method of the AJAX object) is available. At that point, you can put whatever JavaScript you'd like in there to do with the data anything you'd like to. In this case, I put the responseText directly into the div unaltered.

The first thing you'll want to try out is passing name and value pairs, so that you can make your AJAX requests more useful. It is very easy to do this. Here is an example of the open method with some name/value pairs:

ajax.open('GET', 'ajax.php?id=5&page=2', true);

Then on the ajax.php page, you can access these like you normally would with the $_GET superglobal:

<?php
if($_GET['id'] == 5) echo 'ID # 5!';
if($_GET['page'] == 2) // do something



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 "hello" function:

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

We added the setRequestHeader method 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 name/value pairs (using the Math.random() function for example), or you can just use the POST method, which won't be cached by IE.

Comment on this post


Features
Free Web MP3 PlayerComputer Build GuidePHP Beginner Tutorials
Post Series
ActionScript 3 TutorialsHard Drive Cost Charts
Popular Tags
actionscriptajaxcall of dutycrysisebayfacebookgooglejavascriptminecraftneweggphprageskyrimtutorialyoutube


H3XED © 2012 Nick Vogt | Web Design
Saturday, May 19, 2012 | Privacy Policy | Disclosure Policy | Contact