JQuery / Ajax - How to keep the page updated?

2

I have a page that loads with $ .ajax () from JQuery, ajax pulls a page in php with a database that is updated constantly and I need to keep the page up to date, how would it be the best way?

I've read about using a setTimeOut( '', 2000 ); but I thought it would weigh so much that it would be impractical, and I also read about a timeout in jquery's own ajax but it did not work, I updated the database and the page remained the same, I used this example in the script :

$(document).ready(function(){
    site();
});

function site() {
    $.ajax({
        url: "site.php",
        method: 'POST',
        dataType: 'json',
        success: function (data) {
            console.log(data);
        },
        error: function (data) {
            console.log(data);
        },
        timeout: 3000
    });
}

I added timeout this way and nothing has changed!

    
asked by anonymous 04.08.2016 / 16:40

1 answer

2

The setting timeout parameter is the amount of time that ajax should wait for the AJAX response, or "expiration time" (I am not sure of the exact word in Portuguese).

What do you want is an ajax that repeats from N to N seconds, right?

You can do it like this:

$(document).ready(site);

function site() {
    $.ajax({
        url: "site.php",
        method: 'POST',
        dataType: 'json',
        success: function (data) {
            console.log(data);
        },
        complete: function(){
            setTimeout(site, 3000);
        }
    });
}

I used complete because it is always called, if it is successful or not.

    
04.08.2016 / 16:46