Thursday, February 7, 2013

AJAX, First Example (Based on the new Boston website)


As I mentioned, this blog is mostly for me to remember the code I'm learning so I won't be doing much explaining of the code BUT however, I will place links in case I took the examples from some source.


1. Example was basically taken from, I just change'd it a bit since it wasn't really working.

1. You have a working web server supporting php
2. You are familiar with PHP
3. You are familiar with JavaScript

So lets start!
1. Create a file name index.html and copy the code below to the file

<!DOCTYPE html>
 <script type="text/javascript" src="foodstore.js"> </script>
  <input type="text" id="userInput" onkeyup="process()" />
  <div id="underInput" />

2. Create a file name foodstore.js and copy the code below to the file

var xmlHttp = createXmlHttpRequestObject();

function createXmlHttpRequestObject() {

 var xmlHttp;

 if (window.ActiveXObject){
   xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  } catch (e) {
   xmlHttp = false;
   xmlHttp = new XMLHttpRequest();
  } catch (e) {
   xmlHttp = false;

 if (!xmlHttp) {
  alert("Could not create XML Object");
 } else {
  return xmlHttp;

function process() {

  food = encodeURIComponent(document.getElementById("userInput").value);
  //alert(food);"GET", "foodstore.php?food="+food, true);
  xmlHttp.onreadystatechange = handleServerResponse;


function handleServerResponse () {

 if ( xmlHttp.readyState==4 )
  if ( xmlHttp.status==200 || xmlHttp.status == 206) {
  xmlResponse = xmlHttp.responseXML;
  xmlDocumentElement = xmlResponse.documentElement;
  message = xmlDocumentElement.firstChild.textContent;
  document.getElementById("underInput").innerHTML = '<span style="color:blue">' + message + '</span>';

3. Create a file name foodstore.php and copy the code below to the file

 header('Content-Type: text/xml');
 echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';

 echo '<response>';
  $foodArray = array('tuna','bacon','beef','loaf','ham');

  if (in_array($food,$foodArray)) {
   echo "We do have ".$food;
  } elseif ($food==''){
   echo "Enter food";
  } else {
   echo "Sorry, we do not have ".$food;

 echo '</response>';

4. Place the 3 files in a directory under your web server (meaning you can browse it)

5. Surf to the index.html file.

6.You should see text box. Type your name in it and you should see something like this below the text box:
Sorry, we do not have Tzach

7. Type in tune and you should see the following:
We do have tuna