Reputation: 67
I have this problem when I use setInterval
and ajax for retrieving data from the database and if the data that I retrieve from the database is equal to saveHere then it will loop again until it does not match the variable saveHere, it freeze the browser until the data that I retrieve is not equal to saveHere.
Here is an example:
var saveHere = 'RED';
var interval = setInterval(function() {
var sample = $.ajax({
type: 'GET',
url: 'database.php',
data : data
}).responseText;
if (sample != 'RED') {
clearInterval(interval);
saveHere = sample;
}
else {
console.log('load again');
}
},1000);
I really need advice. Thank you in advance. Sorry for the grammar.
Upvotes: 2
Views: 14068
Reputation: 24254
$.ajax
is asynchronous and requires you to use a callback to get the response text.
Take a look at the documentation at http://api.jquery.com/jQuery.ajax/
What you want to do is to add a success
parameter. Something like this:
var saveHere = 'RED';
doAjax();
function doAjax() {
$.ajax({
type: 'GET',
url: 'database.php',
data: data,
success: function (sample) {
if (sample != 'RED') {
saveHere = sample;
} else {
console.log('load again');
doAjax();
}
}
});
}
Notice how I've removed setInterval
and instead wrapped the Ajax code in a function. The success
callback will be called when the Ajax query has successfully finished, and give you the response. Once we have evaluated the response, we can run the doAjax
function again to run the query again.
Upvotes: 7
Reputation: 9661
Without knowing the exact scenario, or what you're looking to achieve, I'd say the way you're going about your AJAX calls is very dangerous as it has the potential to constantly make a request every second, regardless of whether the server has had a chance to respond yet.
I'd be tempted to only make one request at a time, something like:
var saveHere = 'RED';
makeAjaxCall();
function makeAjaxCall() {
var url = 'database.php';
var data = {};
$.get(url, data, function(response_text){
if (response_text != 'RED')
{
saveHere = response_text;
// do whatever else you need...
}
else
{
// make another call...
console.log('calling again...');
makeAjaxCall();
}
}, "text");
}
Upvotes: 2
Reputation: 3299
In your code you test for not equal to 'RED'.
if(sample != 'RED'){ . . .
That part of the loops stops the interval
If it doesn't equal red
}else{
It simple logs 'load again' without clearing the interval
What exactly are you trying to achieve ?
Upvotes: 0
Reputation: 27364
You are clearing interval that means no interval will occur after that.
Instead what you can do is wrap interval inner code inside if condition as below.
var interval = setInterval(function()
{
if(sample != 'RED') {
var sample = $.ajax({
type: 'GET',
url: 'database.php',
data : data
}).responseText;
saveHere = sample;
}
else
{
console.log('load again');
}
},1000);
Upvotes: 0