javascript - Refresh content of a page via AJAX
Get the solution ↓↓↓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
Solution:
I think you should put the counter variable outside function. Otherwise each time this variable will reset to0
;
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);
Answer
Solution:
Seems you need to update yourpageToLoad
also after updating counter as your initial result already stored in your variable and is not changing anymore.
success: function(html) {
pageToLoad = 'likes.php' + "?p=" + ++counter;
}
Answer
Solution:
you are useing 'counter' variable in your 'loadLikes' function and every time you calling 'loadLikes' it's get 0 value .
you have to declare 'counter' variable outside of 'loadLikes' function
var counter = 0;
var loadLikes = function() {
var pageToLoad = 'likes.php' + "?p=" + counter;
$.ajax({
url: pageToLoad,
dataType: 'html',
success: function(html) {
counter++;
/* change your div html here
for example : $(div).html(html);
*/
}
});
console.log(pageToLoad);
};
$(document).ready(function(){
setInterval(loadLikes, 1000);
});
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: too few arguments to function laravel
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.