Ajax Tutorial

When I first tried to learn how to use Ajax, all the tutorials and guides I found online were super confusing. All I wanted was a simple example so I could see how to do it myself. Now, a few years later, I'm offering that very example to all of you…

Ajax can seem daunting at first, but really all you need is a decent knowledge of JavaScript and a few lines of code (which you can find in the example below).

The example is just a silly Magic 8 Ball type thing, but the possibilities of what you can actually do with Ajax are much more exciting. This example includes two different buttons, each with their own request function. They share the same response function, but this doesn't have to be the case – you can send the response to whatever function you want.

In the first step, we create an HTML page to host our form and we include our JavaScript in the <head> section of it:

<script type="text/javascript" language="JavaScript"> 

function setAjax() {
  var xmlHttp = false;
  try {
	xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (e) {
	try {
	  xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
	} catch (e2) {
	  xmlHttp = false;
	}
  }
  if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
	xmlHttp = new XMLHttpRequest();
  }
  return xmlHttp;
}

function ajaxRequest_ask() {
  var url = "../ajax-example-processor.php";
  var question = document.getElementById('question').value;
  var params = "question=" + question + "&action=ask";
  var xmlHttp = setAjax();
  xmlHttp.open("POST", url, true);
  xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xmlHttp.setRequestHeader("Content-length", params.length);
  xmlHttp.setRequestHeader("Connection", "close");
  xmlHttp.onreadystatechange = function() {
	if (xmlHttp.readyState == 4) {
	  if (xmlHttp.status == 200) {
		ajaxResponse(xmlHttp);
	  }
	}
  }
  xmlHttp.send(params);
}

function ajaxResponse(req) {
  var response = req.responseText;
  document.getElementById('response_div').innerHTML = response;
  document.getElementById('response_div').style.display = 'block';
}

function ajaxRequest_repeat() {
  var url = "../ajax-example-processor.php";
  var question = document.getElementById('question').value;
  var params = "question=" + question + "&action=repeat";
  var xmlHttp = setAjax();
  xmlHttp.open("POST", url, true);
  xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xmlHttp.setRequestHeader("Content-length", params.length);
  xmlHttp.setRequestHeader("Connection", "close");
  xmlHttp.onreadystatechange = function() {
	if (xmlHttp.readyState == 4) {
	  if (xmlHttp.status == 200) {
		ajaxResponse(xmlHttp);
	  }
	}
  }
  xmlHttp.send(params);
}

</script>

Next, we add a form within the <body> section of that same HTML page:

<form>
<h3>Ask the Magic 8 Ball</h3>
<div id="response_div" style="display:none; border: 1px black solid; padding: 10px; margin: 10px;"></div>
<p>
  Enter your question:<br>
  <input type="text" id="question" name="question" size="70" maxlength="100" value="" />
</p>
<p>
  <input type="button" class="button" onClick="ajaxRequest_ask()" value="Get Answer" />
  <input type="button" class="button" onClick="ajaxRequest_repeat()" value="Repeat Question" />
</p>
</form>

Finally, we create a processor to handle the requests that get sent by the Ajax call. The cool thing with this is that you can use PHP functions and even access your MySQL database, etc. without having to reload the page. In this simple example, this file is called ajax-example-processor.php. Here's the code:

<?php

header('content-type:text/plain');

//clean up incoming data
$fields = array('question','ask','action');
foreach ($fields as $key) {
	if (array_key_exists($key,$_REQUEST) && is_string($_REQUEST[$key])) { $$key = strip_tags($_REQUEST[$key]); } else { $$key = false; }
}
//respond to input
if (!$question) { echo 'Error: You didn\'t enter a question.' ; }
elseif (substr($question,-1) != '?') { echo 'Error: Your question must end with a question mark.' ; }
else {
	if ($action == 'ask') {
		$x = rand(1,2);
		if ($x == 1) { echo 'The answer to your question is yes.'; }
		else { echo 'The answer to your question is no.'; }
	} elseif ($action == 'repeat') {
		echo 'Your question was:<br><br>'.htmlspecialchars($question);
	} else { echo 'Error: Unknown action.' ; }
}
?>

That's it. Pretty simple. Play around with the this example and see how it works for yourself:

Ask the Magic 8 Ball

Enter your question:

Update: You should know that there are much easier ways of performing Ajax calls these days, such as jQuery's Ajax functions. However, I've left this here in case your particular application requires Ajax without a library like jQuery for some reason.


Comments

Loading…

This post was first published on September 18th, 2010 and last updated on September 20th, 2014 by Robert James Reese in the following categories: Ajax, JavaScript, and PHP. Before using any of the code or other content in this post, you must read and agree to our terms of use.