How do I make Ajax update every 10 seconds in jquery? - ajax

How do I make Ajax update every 10 seconds in jquery?
$.ajax({
type: "GET",
url: options.feedUrl,
dataType: "xml",
async:options.sync,
success: function(xml) {
}
For example I am testing the jquery above to get a RSS feed. So how do you make it update the RSS every 10 seconds so the user can see a new item in the feed?

Creating an interval
var ResInterval = window.setInterval('myAjaxCall()', 60000); // 60 seconds
var myAjaxCall = function() {
$.ajax({
type: "GET",
url: options.feedUrl,
dataType: "xml",
async:options.sync,
success: function(xml) {
// todo
}
};
To stop
window.clearInterval(ResInterval);

I'd avoid the synchronous ajax call. It'll make anything else on the page like animations freeze. Of course with asynchronous calls you'll need to make sure they don't start overlapping. In your setInterval you could just put a lock:
var doingAjax = false;
setInterval(function() {
if (!doingAjax) {
doingAjax = true;
jQuery.ajax({
...,
success: function() {
doingAjax = false;
...
}
});
}
};

wrap it in a function and use setInterval()

Related

jQuery.ajax request progress bar

Okay, this is the same post as my last post which got downvoted and marked as duplicate. Here's the post again but now with the explaination why the questions from What is the cleanest way to get the progress of JQuery ajax request? didn't work.
I have an AJAX request in where I insert stuff in the database and send 2
emails. I'd like to show the progress of the AJAX request.
Currently I tried:
$.ajax({
type: 'POST',
url: '/ajax/submit_order_form.php',
data: form_data,
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.addEventListener('progress', function(e) {
if (e.lengthComputable) {
$('title').html((100 * e.loaded / e.total) + '%');
}
});
return xhr;
},
complete: function() { /*here some stuff*/ }
});
However, it doesn't change the title during the request, but after the request it sets it to 100%. Is there any way I can get what I want? So that when 50% in the AJAX file is executed it shows 50% and does the progress like that.
The next thing I tried is:
$.ajax({
type: 'POST',
url: '/ajax/submit_order_form.php',
data: form_data,
chunking: true,
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
$('title').html(percentComplete);
//Do something with upload progress here
}
}, false);
xhr.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
$('title').html(percentComplete);
//Do something with download progress
}
}, false);
return xhr;
},
complete: function (result){}});
However then I only get a 1 in the title, and immediately when I click my button and the AJAX gets called.
Last, I tried the second answer:
$.ajax({
type: 'POST',
url: '/ajax/submit_order_form.php',
data: form_data,
chunking: true,
complete: function (result) {}
}).progress(function(e, part) {
console.log(part);
}).progressUpload(function()
{
});
However this gives:
jq-ajax-progress.min.js:1 Uncaught TypeError: Cannot read property 'upload' of undefined
at Function.e.ajax (jq-ajax-progress.min.js:1)
at a.validator.submitOrderForm (checkout.js:108)
at d (jquery.validate.min.js:4)
at HTMLFormElement.<anonymous> (jquery.validate.min.js:4)
at HTMLFormElement.dispatch (jquery.min.js:3)
at HTMLFormElement.r.handle (jquery.min.js:3)
I tried a lot of things already but none seem to work.

Can't post ajax value

Still stack in these code. On any browser desktop working fine, but when try use chrome on my android, can't post value from ajax datastring.
jQuery(document).ready(function()
{
jQuery(".button").click(function()
{
var product = jQuery(".products").val().split('|')[0];
var nomortujuan = jQuery(".nomortujuan").val();
var pn = parseFloat(document.getElementById("val[pin]").value);
var dataString = 'method=sendMessage&message='+product+'.'+ nomortujuan+'.'+pn;
var web = 'ajax.php';
jQuery.ajax ({
type: "POST",
url: web,
data: dataString,
cache: true,
beforeSend: function(html) {
document.getElementById("hasil").innerHTML = '';
jQuery(".flash").show();
jQuery(".flash").html('<div style="float:left;"></div>');
},
success: function(html){
jQuery("#js_process_request input, #js_process_request select").attr('disabled',false);
jQuery(".flash").hide();
jQuery("#hasil").hide();
jQuery ("#hasil").append(html);
return false;
}
});
});
});
Maybe this problem
jQuery ("#hasil").append(html);
remove spacing to fix it
jQuery("#hasil").append(html);

prevent calling ajax multiple times

I am trying to figure out ways to prevent ajax from being called multiple times. Below is my code. I created a scrollable div, my goal is, once the scroll inside this div is about to reach the bottom, I want to call the ajax. Everything works so far. But the problem is, whenever I scroll the div fast enough to the bottom, the ajax is being called multiple times.
$('.scroll_div').scroll(function(){
var scroll_pos = $(this).scrollTop();
var outer_height = $(this).height();
var inner_height = $(this)[0].scrollHeight;
var scroll_end = scroll_pos + outer_height;
if(scroll_end >= inner_height-300){
$.ajax({
type: 'POST',
url: 'ajax/get_info.php',
data: {data_type: data_type},
beforeSend:function(){
}
}).done(function(data){
alert(data);
});
}
});
I would put a timer on it - adjust the timeout accordingly, so that the ajax would only fire if the user stays put for a second or two:
$('.scroll_div').scroll(function(){
if(typeof(myTimer)!='undefined'){
clearTimeout(myTimer);
}
var scroll_pos = $(this).scrollTop();
var outer_height = $(this).height();
var inner_height = $(this)[0].scrollHeight;
var scroll_end = scroll_pos + outer_height;
if(scroll_end >= inner_height-300){
//timer
myTimer = window.setTimeout(function(){
$.ajax({
type: 'POST',
url: 'ajax/get_info.php',
data: {data_type: data_type},
beforeSend:function(){}
}).done(function(data){
alert(data);
});
}, 2500);
}
});

Restructuring nested ajax calls so variables work

My "value" variables below are not being inherited into the second call. What is the recommended way to reconstruct this so that it works?
First, I get all the data from our data table. Then, I need to get pending changes from a completely different database (change control). I need to display the second data if it exists.
function getData(appid) {
$.ajax({
url: 'services/getData',
type: 'GET',
data: { 'appid': appid },
dataType: 'json',
success: function (data) {
var field1Value = data.field1;
var field2Value = data.field2;
var field3Value = data.field3;
//get pending changes
$.ajax({
url: 'services/getPendingChanges',
type: 'GET',
data: { 'appid': appid },
dataType: 'json',
success: function (data2) {
if (data2.field1 <> '') { field1value = data2.field1 };
if (data2.field2 <> '') { field1value = data2.field2 };
if (data2.field2 <> '') { field1value = data2.field2 };
},
complete: function () {
//set data in UI regardless of whether it came from getData or getPendingChanges
$('#txtField1').html(field1value);
$('#txtField2').html(field2value);
$('#txtField3').html(field3value);
}
})
}
})
}
of course when I do this, all the "*value" variables are undefined.
Unsure whether this will help you at all (and it probably won't), but this is what I've learned in my time in Javascript. But the nature of anon classes in javascript are so that you can use them without worry of variable collisions. The easiest way is that you funnel up to a higher scope variable to use later. But that's generally bad practice... So you could throw a wrapper around all that...
I ended up hiding the fields then calling the second ajax from the complete of the first. I set the fields in the success of the first call and also in the success of the second call, if they exist. Then I unhide them in the complete of the second.
function getData(appid) {
$('#txtField1').hide();
$('#txtField2').hide();
$('#txtField3').hide();
$.ajax({
url: 'services/getData',
type: 'GET',
data: { 'appid': appid },
dataType: 'json',
success: function (data) {
var field1Value = data.field1;
var field2Value = data.field2;
var field3Value = data.field3;
$('#txtField1').html(field1value);
$('#txtField2').html(field2value);
$('#txtField3').html(field3value);
},
complete: function () {
//get pending changes
$.ajax({
url: 'services/getPendingChanges',
type: 'GET',
data: { 'appid': appid },
dataType: 'json',
success: function (data2) {
if (data2.field1 <> '') {
field1value = data2.field1
$('#txtField1').html(field1value);
};
if (data2.field2 <> '') {
field2value = data2.field2
$('#txtField2').html(field2value);
};
if (data2.field3 <> '') {
field3value = data2.field3
$('#txtField3').html(field3value);
};
},
complete: function () {
$('#txtField1').show();
$('#txtField2').show();
$('#txtField3').show();
}
})
}
})
}
Ultimately instead of hiding them I would swap them out with a loading indicator. Also, I realize the BEST thing to do would be have a single web service that did all the logic in the background and just returned the appropriate data.

jQuery recursive ajax poll using setTimeout to control the poll interval

$(document).ready(function() {
(function poll() {
setTimeout(function() {
$.ajax({
url: "/project1/api/getAllUsers",
type: "GET",
success: function(data) {
console.log("polling");
},
dataType: "json",
complete: poll,
timeout: 5000
}), 5000
});
})();
});​
This just keeps executing as fast as the server can respond but I was hoping it would only poll every 5 seconds. Any suggestions?
EDIT: I should add, 5 seconds after the request has completed would be preferable.
It seems that you've managed to get your setTimeout delay argument written in the wrong place.
$(document).ready(function() {
(function poll() {
setTimeout(function() {
$.ajax({
url: "/project1/api/getAllUsers",
type: "GET",
success: function(data) {
console.log("polling");
},
dataType: "json",
complete: poll,
timeout: 5000
}) //, 5000 <-- oops.
}, 5000); // <-- should be here instead
})();
});​
If you follow the braces, you'll see that you're calling setTimeout like:
setTimeout(function () {
$.ajax(), 5000
})
and should be
setTimeout(function () {
$.ajax();
}, 5000)
This should call the AJAX poll 5 seconds after the previous one has completed.
If it should poll every 5 seconds and not necessarily 5 seconds after completing the last request, you could use setInterval. Don't know if that's acceptable, but it would make recursion unnecessary.
function poll() {
$.ajax({
url: "/project1/api/getAllUsers",
type: "GET",
success: function(data) {
console.log("polling");
},
dataType: "json"
});
}
setInterval(poll, 5000);
Incase you wanted to use jQuery's promise syntax, rather than callback syntax here's another tidy way.
function poll() {
$.get('http://your-api-endpoint.com')
.done(function() {
// 200 - OK response
})
.fail(function() {
// Error Response
})
.always(function () {
setTimeout(function() {
poll();
}, 5000);
});
}
poll();

Resources