DBS
DBS

Reputation: 301

AJAX tutorial not working

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:

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!

Upvotes: 2

Views: 3188

Answers (5)

Srajan Soni
Srajan Soni

Reputation: 86

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

Upvotes: 0

Nate May
Nate May

Reputation: 4072

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.

Upvotes: 1

mirzak
mirzak

Reputation: 1057

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 !');
    }
}
}

Upvotes: 5

Joseph Ville
Joseph Ville

Reputation: 36

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/

Upvotes: 2

zsawaf
zsawaf

Reputation: 2011

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 :)

Upvotes: 3

Related Questions