A Begginer Question In Ajax.

Discussion in 'PHP' started by Sayedtaqui, Feb 14, 2013.

  1. #1
    Hi,
    I have recently started learning AJAX from a tuorial and I m having a problem with my code, I wrote a script so when a user enters some food name they should instantly get a message while they are typing(whether that food is available or not , I didnt create a database, just wrote an array). But the code isn't working. I created three files for this purpose and here are those files
    The INDEX file...
    
     
     
    <!DOCTYPE html>
    <head>
    <script type="text/javascript" src="foodstore.js"></script>
    </head>
     
    <body onload="process()">
     
            <h3>The Chuff Bucket</h3>
            Enter the food you want to order:
            <input type="text" id="userInput" />
            <div id="underInput"></div>
     
    </body>
    </html>
     
     
    
    Code (markup):
    the other php 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 a food you idiot';
              }
              else{
                  echo "Sorry punk we dont sell no '$food' ";
                  }
     
     
    echo '</response>';
     
     
    ?>
     
    
    Code (markup):

    AND the javascript file...

    
     
    // JavaScript Document
     
    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("cant create that object hoss!");
          else
                  return xmlHttp;
      }
     
    function process(){   
        if(xmlHttp.readyState==0 || xmlHttp.readyState==4){
          food=encodeURIComponent(document.getElementById("userInput").value );
          xmlHttp.open("GET", "foodstore.php?food=" + food, true);
          xmlHttp.onreadystatechange = handleServerResponse;
          xmlHttp.send(null);
          }else{
              setTimeout('process()', 1000);
              }
      }
     
     
    function handleServerResponse(){
      if(xmlHttp.readyState==4){
                  if(xmlHttp.status==200){
                      xmlResponse=xmlHttp.responseXML;
                      xmlDocumentElement=xmlResponse.documentElement;
                      message=xmlDocumentElement.firstChild.data;
                      document.getElementById('underInput').innerHTML='<span style="color:blue">' +message + '</span>';
                      seTimeout('process(), 1000');
              }else{
                  alert('Something went wrong!');
                  }
          }
      }
     
    
    Code (markup):

    Please help me debug this code. Thanks in advance.
     
    Solved! View solution.
    Sayedtaqui, Feb 14, 2013 IP
  2. ezprint2008

    ezprint2008 Well-Known Member

    Messages:
    611
    Likes Received:
    15
    Best Answers:
    2
    Trophy Points:
    140
    Digital Goods:
    1
    #2
    did you stop posting all your code or did you really forget to put a
    
    <form name="your_form" method="GET" action="your_page.php">
    
    HTML:
    ?
     
    ezprint2008, Feb 14, 2013 IP
  3. Sano000

    Sano000 Active Member

    Messages:
    52
    Likes Received:
    4
    Best Answers:
    5
    Trophy Points:
    53
    #3
    Hi, It 21th century now, we can use jquery :)

    For example
    index.html
    <!DOCTYPE html>
    <head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
    <script type="text/javascript" src="foodstore.js"></script>
    </head>
     
    <body>
     
            <h3>The Chuff Bucket</h3>
            Enter the food you want to order:
            <input type="text" id="userInput" />
            <div id="underInput"></div>
     
    </body>
    </html>
    HTML:
    foodstore.js
    
    $(document).ready(function() {
      $('#userInput').bind('keyup', function(){
        $.ajax({
          url: 'foodstore.php?food='+$(this).val(),
          success: function(data){
            $('#underInput').html(data);
          }
        });
      });
    });
    
    Code (markup):
    foodstore.php
    
    <?php
      $food=$_GET['food'];
      $foodArray= array('tuna','bacon', 'beef', 'loaf', 'ham');
     
      if(in_array($food, $foodArray)){
          echo "We do have ". $food;
      } elseif($food==''){
          echo 'Enter a food you idiot';
      } else {
        echo "Sorry punk we dont sell no '$food' ";
      }
    ?>
    
    PHP:
    Some tricks: you can use console.log('message') and web console in a browser (F12 on the chrome) to debug code yourself.
     
    Sano000, Feb 14, 2013 IP
  4. #4
    You missed a T in setTimeout. Might also help if your code indentation made any sense whatsoever...
     
    deathshadow, Feb 14, 2013 IP
  5. Sayedtaqui

    Sayedtaqui Greenhorn

    Messages:
    46
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    6
    #5
    HEY thanks sano, and deathshadow. Though I wasn't looking for doing it with jquery but thanks for telling me that. its good to have options. Finally it worked , thanks to Deathshow , I never noticed that missing T. I debugged the code a little more and it started working. Thanks a lot to both of you.
     
    Sayedtaqui, Feb 14, 2013 IP