Jquery/Ajax - How to keep the page up to date?

Asked

Viewed 150 times

2

I have a page that is loaded with $.ajax() from Jquery, ajax pulls a page in php with a database that is constantly updated and need to keep the page updated, as serious the best way ?

I read about using a setTimeOut( '', 2000 ); but I thought it would weigh so much q would be unviable, and I also read about a timeout in jquery’s own ajax but it didn’t work, I updated the database and the page stayed 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 the timeout this way and nothing has changed!

1 answer

2

The parameter of configuration timeout is the interval of time that ajax must wait for the answer of AJAX, ie "expiry time" (I am not sure of the exact word in Portuguese).

What you want is an ajax that repeats itself of N in 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 the complete For it is called always, whether it succeeds or not.

  • Hi Sergio, this is the best way ? would not be too heavy the site ?

  • 1

    This is one way. Every 3 seconds it refreshes. If you search a lot of content is heavy. But in this case the technique is not the problem but the amount of data that you search without filtering out what is needed or not. You can use sockets and have a constant connection, but if you don’t need this solution it sounds good :) You can use React to manage what is inserted in the DOM or not, but if it’s that simple thing it should be enough.

  • The websockets tend to be more economical, as the server informs the client when there has been a change, rather than the client repeatedly asking if something has changed. But the implementation of this is not so simple.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.