2

I was following Bucky's (the new boston) tutorial on Ajax and got stuck right on the 1st lesson =|

Here's my problem:

Ajax isn't working. I set some checkpoint alerts on .js and found that "readyState" never hits 4 - I only get 3 alerts:

  • f(process) 1st checkpoint - readyState: 0
  • f(process) 2nd checkpoint - readyState: 0
  • f(handleServerResponse) 1st checkpoint - readyState: 1

I'm running on localhost with Xampp, browsers are Chrome and Firefox.

Here's the code:

index.html:

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="foodstore.js"></script>
    </head>
    <body onload="process()">
        <h3>The Chuff Bucket</h3>
        Enter the food you would like to order:
        <input type="text" id="userInput" />
        <div id="underInput" />
    </body>
</html>

foodstore.php:

<?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>';

?>

foodstore.js:

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(){
    alert("1st checkpoint f(process) - readyState: " + xmlHttp.readyState);//
    if(xmlHttp.readyState==0 || xmlHttp.readyState==4){
        alert("2nd checkpoint f(process) - readyState: " + xmlHttp.readyState);//
        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(){
    alert("1st checkpoint f(handleServerResponse) - readyState: " + xmlHttp.readyState);//
    if(xmlHttp.readyState==4){
        alert("2nd checkpoint f(handleServerResponse) - readyState: " + xmlHttp.readyState);//
        if(xmlHttp.status==200){
            xmlReponse = xmlHttp.responseXML;
            xmlDocumentElement = xmlReponse.documentElement;
            message = xmlDocumentElement.firstChild.data;
            document.getElementById("underInput").innerHTML = message;
            //setTimeout('process()', 1000);
        }else{
            alert('Something went wrong!');
        }
    }
}

Any help appreciated!

DBS
  • 191
  • 2
  • 14
  • 1
    Have you thought of using jQuery instead? – zsawaf Sep 01 '14 at 03:28
  • 3
    the first problem is `xmlHttp.onreadystatechange = handleServerResponse();`.. you need to assign a function reference to the statechange don't invoke the function `xmlHttp.onreadystatechange = handleServerResponse;` – Arun P Johny Sep 01 '14 at 03:29
  • @zsawaf Yeah I did, no success. I have tried everything actually, this tutorial being my last resort... I'm stuck with Ajax for days already. – DBS Sep 01 '14 at 03:31
  • you are trying to read the value of `userInput` in `onload` handler... where it is empty... probably you might want to use a click handler? – Arun P Johny Sep 01 '14 at 03:33
  • try something like http://jsfiddle.net/arunpjohny/kp36er5u/1/ – Arun P Johny Sep 01 '14 at 03:38
  • Guys I do appreciate the jQuery tips (with $.get, $.ajax etc.), but I'm sure this can be done without it. I'll accept an answer that points out the problem and correction, not a new solution, is that fare? – DBS Sep 01 '14 at 16:42
  • Arun P Johny's comment helped me get to readyState 4!!! I erased the parenthesis on `xmlHttp.onreadystatechange = handleServerResponse;` – DBS Sep 12 '14 at 22:06

5 Answers5

5

This is from Bucky's AJAX tutorials. And if you are interesed here is full working code :

index.html

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="foodstore.js"></script>
</head>
<body onload="process()">
    <h3>The Chuff Bucker</h3>
    Enter the food you would like to order:
    <input type="text" id="userInput" />
    <div id="underInput" />
</body>
</html>

foodstore.php

<?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','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>';
?>

foodstore.js

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 !")
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);//cekaj 1s pa probaj opet
}
}

function handleServerResponse(){
if(xmlHttp.readyState==4){ 
    if(xmlHttp.status==200){
        xmlResponse = xmlHttp.responseXML; //izvlaci se xml sto smo dobili
        xmlDocumentElement = xmlResponse.documentElement;
        message = xmlDocumentElement.firstChild.data;
        document.getElementById("underInput").innerHTML = message;
        setTimeout('process()', 1000);
    }else{
        alert('Someting went wrong !');
    }
}
}
mirzak
  • 1,043
  • 4
  • 15
  • 30
  • I'm getting an [ Uncaught TypeError: Cannot read property 'documentElement' of null ] with this code. The error points to line 41 in foodstore.js, xmlDocumentElement = xmlResponse.documentElement; – Brent Connor Mar 04 '15 at 15:48
  • Helped a lot Cheers! *Make Sure* to check if you set the headers of your php XML file to text/xml NOT text/html like I did obliviously – Matthcw Jul 02 '15 at 22:19
3

Here is how I would approach the problem.

var userInput = $("#userInput").val();
$.ajax({
   url: 'foodstore.php',
   data: userInput,
   method: 'GET',
   success: function(response){
       $("#underInput").html(response);
   }
});

A lot cleaner as you can see! And does the same thing :)

zsawaf
  • 1,921
  • 16
  • 24
2

In foodstore.js, inside process(), replace this line:

xmlHttp.onreadystatechange = handleServerResponse();

with this line:

xmlHttp.onreadystatechange = handleServerResponse;

This is because you are passing the function itself, not the return value after the function is called. See http://www.reddit.com/r/learnprogramming/comments/24iqej/javascriptjquery_why_are_parentheses_not_always/

  • With this correction it made it to readyState 4 and status 200, but for some reason ajax is still not working... – DBS Apr 21 '17 at 21:50
  • 1
    Actually, after I set the timer back on and refreshed the page a few times, it did start working. Thanks Joseph! – DBS Apr 21 '17 at 22:08
1

When I was having trouble with this, I changed this line

alert('Someting went wrong !');

to this:

alert('Someting went wrong ! readyState = ' + xmlHttp.readyState + ', Status = ' + xmlHttp.status);

I noticed that my status was always 0, so I looked in my console and got this error:

XMLHttpRequest cannot load file: foodstore.php?food="+food

Looking into this error I found this answer to a similar problem.

Basically, my browser was blocking my XMLHttpRequest request for security reasons. I upload these files (+ bug fixes) to a personal web server and the AJAX worked! There are also several other workarounds listed in the link above.

Community
  • 1
  • 1
Nate May
  • 3,814
  • 7
  • 33
  • 86
0

Make sure that the folder you are working is in the htdocs folder of XAMPP!

Srajan Soni
  • 86
  • 3
  • 12