Reputation: 5273
I have a function defined like this:
function call_view_details(viewid)
{
view_details(viewid);
setInterval(function(){view_details(viewid)},5000);
}
which i call at page load. Mainly it sets interval for view_details()
.
Here's view_details()
:
function view_details(viewid)
{
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("item_details").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","view_item.php?id="+viewid,true);
xmlhttp.send();
return false;
}
As you can see, view_details()
updates some div
with view_item.php
's response.
But i want on some cases (which happen in view_item.php
), to execute clearInterval()
on view_details()
.
Now i don't want to say:
if(xmlhttp.responseText==/*something*/)
/*clearInterval*/
That's because, first, there are a lot of cases, and second, also in those cases view_item.php
echos something i need to update the div
with.
So maybe i can let view_item.php
pass some variable in addition to its response? And then i can make a condition on that variable.
I hope it's clear enough...
Thank you
Upvotes: 0
Views: 274
Reputation: 2113
Return a JSON object.
view_item.php
<?php
// PHP stuff
$returnArray = array();
$returnArray['message'] = $yourRespondText;
$returnArray['clearInterval'] = true; // return true when you want to call clearInterval
echo json_encode($returnArray);
JS:
function call_view_details(viewid)
{
view_details(viewid);
var interval = setInterval(function(){view_details(viewid, interval )},5000);
}
function view_details(viewid, yourInterval)
{
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
data = JSON.parse(xmlhttp.responseText);
if(data.clearInterval) {
clearInterval(yourInterval);
}
document.getElementById("item_details").innerHTML=data.message;
}
}
xmlhttp.open("GET","view_item.php?id="+viewid,true);
xmlhttp.send();
return false;
}
Upvotes: 1