Thursday, February 7, 2013

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

Hi,

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.

Sources

1. Example was basically taken from http://www.youtube.com/watch?v=tp3Gw-oWs2k, I just change'd it a bit since it wasn't really working.
2. http://www.w3schools.com/ajax/

Assumptions:
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>
<html>
<head>
 <script type="text/javascript" src="foodstore.js"> </script>
</head>
 <body>
  <input type="text" id="userInput" onkeyup="process()" />
  <div id="underInput" />
 </body>
</html>

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){
  try{
   xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  } catch (e) {
   xmlHttp = false;
  }
 }else{
  try{
   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);
  xmlHttp.open("GET", "foodstore.php?food="+food, true);
  xmlHttp.onreadystatechange = handleServerResponse;
  xmlHttp.send();

}

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

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

 echo '<response>';
  $food=$_GET['food'];
  $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