When a button is clicked I have a jquery AJAX call such as:
$(".play").click(function(){
function doAjax(){
$.ajax({
url: 'blah.php',
success: function(data) {
if (data==250)
{
setTimeout(doAjax, 2000);
}
else
{
$('#quote p').html(data);
}
}
});
}
doAjax();
});
Any data from the server is printed to the div:
<div id="quote"><p> </p></div>
blah.php on the server does some processing to retrieve some status codes:
$r = new HttpRequest('http://localhost...', HttpRequest::METH_GET);
$r->send();
if ($r->getResponseCode() == 200)
{
echo "Starting video..."
//sends a video to play
}
else if ($r->getResponseCode() == 450)
{
echo "Oops! Not found...";
}
else if ($r->getResponseCode() == 550)
{
echo "Oops! An error occurred...";
}
else if ($r->getResponseCode() == 250)
{
echo "Initializing...";
}
else
{
echo "Now we are in trouble";
}
The response codes ($r->getResponseCode()) get returned as I expect, so my problem is with my repeated ajax call with setTimeout. What I want to happen is that when code 250 is returned it prints out Initializing, which it does, but then my AJAX call will repeat because the success function is called with 250. This doesn’t work. It says Initializing but never repeats, because the next step is that I should see Starting video....
Everything else seems to check out, I guess the problem is with my jquery success function?
The problem here is that the “data” variable that you have access to in Javascript is actually the exact text that you’re echoing in your PHP file, blah.php.
So a more accurate way of making it work is checking if data == “Initializing…”. You may also want to consider outputting JSON-compatible text from your PHP file so that you can get both a status code and a message.
Consider putting this as your PHP:
The above will output all the data you need, in JSON format.
In your javascript, consider using jQuery’s built in getJSON method, and parse the data as a regular javascript object.