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

14 comments:

  1. still getting error as below while typing tuna

    XML Parsing Error: not well-formed Location: http://10.29.73.14:9082/unifyd2/selfhelp/TEST/Ajax/foodstore.php?food=tuna Line Number 5, Column 8:

    ReplyDelete
    Replies
    1. You probably forgot to close some line with ; in the Java script. Can you paste your code?

      Delete
  2. I've tested it again, it seems okay (see here: http://tzachs.no-ip.biz/examples/ajax/example1/)
    Seems like your php file isn't closed okay (that would be my guess)

    ReplyDelete
  3. Hey why is bucky's code not working but your's is?

    ReplyDelete
    Replies
    1. I don't know. I need to see how you implemented your code. Could you please paste it (If it's not too long)

      Delete
    2. Bucky's javascript file was using the send function as

      send(null)

      but here tzach uses it as

      send()

      just change that xmlHttp.send(null) to xmlHttp.send() and it'll start working.

      btw tzach does the send function return a null ??

      Delete
    3. Hi Showmik Bose,

      According to https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest, the signature for send() is void so I believe there isn't a return value.

      Delete
  4. Thanks a lot. The code completely works but I have a question and that is in foodstore.js on the line

    xmlHttp.onreadystatechange = handleServerResponse;

    In that line, handleServerResponse is basically a function and when calling a function, shouldn't there be empty roundbrackets at the end like this:

    xmlHttp.onreadystatechange = handleServerResponse();

    ReplyDelete
    Replies
    1. Hi Inzamam,

      Sorry it took me a long time to respond.

      I do not wish to call and execute the function at that point, I want to someone to call my function which is named handleServerResponse only when ready state changed, thus, it's called onreadystatechange.

      Meaning, What you see at the line is assigning a pointer to the function, meaning, variable onreadystatechange will have the memory address of the handleServerResponse function.

      That is why we do not place the () there

      Delete