Razvan Zamfir Razvan Zamfir - 15 days ago 5
Javascript Question

Refresh content of a page via AJAX

I need to load a likes into a div via AJAX, every second.

The page's name should be likes.php?p=0 on page load, likes.php?p=1 after 1 second, likes.php?p=2 afrer 2 seconds, and so on.

My code:

var loadLikes = function() {
var counter = 0;
var pageToLoad = 'likes.php' + "?p=" + counter;

$.ajax({
url: pageToLoad,
dataType: 'html',
success: function(html) {
counter++;
}
});
console.log(pageToLoad);
}

$(window).load(loadLikes);
setInterval(loadLikes, 1000);


The console (strangely, in my opinion) shows likes.php?p=0.

What am I doing wrong?

Thank you!

Answer

I think you should put the counter variable outside function. Otherwise each time this variable will reset to 0;

var counter = 0;

var loadLikes = function() {

var pageToLoad = 'likes.php' + "?p=" + counter;

$.ajax({
    url: pageToLoad,
    dataType: 'html',
    success: function(html) {
        counter++;
    }
});
console.log(pageToLoad);    
}

$(window).load(loadLikes);
setInterval(loadLikes, 1000);