Skip to content Skip to sidebar Skip to footer

Setinterval And Ajax

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 a

Solution 1:

$.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();

functiondoAjax() {

    $.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.

Solution 2:

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();

functionmakeAjaxCall() {
    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");
}

Solution 3:

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

Solution 4:

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 ?

Post a Comment for "Setinterval And Ajax"