How to repeat jQuery ajax call every 10 seconds?
$(document).ready(function() {
$.ajax({
type: "GET",
url: "newstitle.php",
data: "user=success",
success: function(msg) {
$(msg).appendTo("#edix");
}
});
I've tried to wrap the $.ajax with a function and to call the function with setInterval
$(document).ready(function() {
function ajaxd() {
$.ajax({
type: "GET",
url: "newstitle.php",
data: "user=success",
success: function(msg) {
$(msg).appendTo("#edix");
}
});
}
setInterval("ajaxd()",10000);
});
But it says "ajaxd is not defined"
Your method should not be placed inside the ready method, or it would only be available there and not outside.
$(document).ready(function() {
setInterval("ajaxd()",10000);
});
function ajaxd() {
$.ajax({
type: "GET",
url: "newstitles.php",
data: "user=success",
success: function(msg){
$(msg).appendTo("#edix");
}
});
}
Better approach would be to use setTimeout
, so you only make a request when the previous one is done.
How it should be done
Imagine that request for some reason (server malfunction, network error) takes longer than defined time. You'll have many simultaneus requests, which isn't any good. And what if you decide to shorten the time difference from 10 seonds to 1 second in the future?
$(function() {
var storiesInterval = 10 * 1000;
var fetchNews = function() {
console.log('Sending AJAX request...');
$.ajax({
type: "GET",
url: "newstitles.php",
data: {
user: 'success',
some: ['other', 'data']
}
}).done(function(msg) {
$(msg).appendTo("#edix");
console.log('success');
}).fail(function() {
console.log('error');
}).always(function() {
// Schedule the next request after this one completes,
// even after error
console.log('Waiting ' + (storiesInterval / 1000) + ' seconds');
setTimeout(fetchNews, storiesInterval);
});
}
// Fetch news immediately, then every 10 seconds AFTER previous request finishes
fetchNews();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I know, after 6 years. But still, I thought it's worth for other people.
Why the OP's code didn't work?
It's worth noting that your code didn't work mainly, because you passed your ajaxd()
function call as a string to setInterval
. It's not a good practice, partly because setInterval
will expect the functions to be defined globally. You should use reference to a function, like in my example. That way, it doesn't matter where your function is defined and if it's anonymous or not.
$(document).ready(function() {
setInterval(function() {
$.ajax({
type: "GET",
url: "newstitle.php",
data: "user=success",
success: function(msg){
$(msg).appendTo("#edix");
}
});
}, 10000);
});