javascript polling at given time interval - javascript

Following function is being called at every 10 second.
function getData()
{
$.ajax({
url : "refresh.php",
type : "POST",
data : {"id" : id},
success : function(data) {
$(".show").html(data);
}
});
}
$(document).ready(function(){
setInterval("getData()",50000);//Polls in every 50 sec
});
What I want is: when page is loaded, getData() should be called instantly, after that each call should be at given interval i.e. 50second
how to do this?

Just add a manual call to getData() in the dom ready handler
function getData() {
$.ajax({
url: "refresh.php",
type: "POST",
data: {
"id": id
},
success: function (data) {
$(".show").html(data);
}
});
}
$(document).ready(function () {
setInterval("getData()", 50000); //Polls in every 50 sec
getData(); //invoke on page load
});

Call the function from the ready event.
Also, use the function reference in the setInterval call rather than a string.
$(document).ready(function(){
setInterval(getData,50000);
getData();
});

Related

.focusout() fires twice on second event jQuery

When I am using the .focusout() function in jQuery it seems to fire twice when I trigger the event for the second time, here is an example of my code:
$(document).ready(function() {
var baseUrl = "http://annuityadvicecentre.dev/";
if($('html').hasClass('ver--prize-soft')) {
$('#home_telephone').focusout(function () {
var softResponse = {};
var inputVal = $(this).val();
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
$.ajax({
type: 'POST',
url: baseUrl + "lookup",
data: {
number: inputVal,
phone_type: "mobile",
},
error: function() {
console.log('POST Error: Mobile');
},
}).done(function(data) {
// you may safely use results here
softResponse.isMobile = data;
});
$.ajax({
type: 'POST',
url: baseUrl + "lookup",
data: {
number: inputVal,
phone_type: "landline",
},
error: function() {
console.log('POST Error: Landline');
},
}).done(function(data) {
// you may safely use results here
softResponse.isLandline = data;
});
$(document).ajaxStop(function () {
console.log('All AJAX Requests Have Stopped');
});
});
}
});
Sorry for the messy example as I have just been bootstrapping this up however you can see I am wrapping this focusout function:
$('#home_telephone').focusout(function () {...
Around my AJAX calls, now for some reason when I test this out on the page and un-focus on the #home_telephone element the .ajaxStop() function only runs once which is the functionality I want however if I then click on the element and un-focus again the .ajaxStop() function runs twice. Any idea why this might be happening? Thanks
Try to add e.stoppropogation() within function like:
$('#home_telephone').focusout(function (e) {
e.stopPropagation()();
//your code
});
You're adding a new ajaxStop listener every time the element is unfocused. Just move the:
$(document).ajaxStop(function () {
console.log('All AJAX Requests Have Stopped');
});
call outside of the focusout callback function.

How to wait a in a for loop until ajax call finishes

I'm new to developing web sites and I'm developing a small web site. Here I'm using ajax to show new comments. this is the function I wrote
function show_comments() {
$('div#P_all_posts>div').each(function () {
id = this.id.replace("post", "");
$.ajax({
url: 'http://localhost/seppro/index.php/group/show_comments',
type: 'post',
data: {
id: id
},
success: function (data) {
document.getElementById("cmnt"+id).innerHTML=data;
},
error: function (err, req) {
alert(err)
},
async: false
});
});
setTimeout("show_comments()", 5000);
}
The PHP
model
public function showcmnts(){
$sql="select * from tbl_cmnt
where postid='".$this->input->post("id")."'";
$query = $this->db->query($sql); return $query->result();
}
controller
public function show_comments(){
$data['cmntlist'] = $this->Group_model->showcmnts();
$this->load->view('group/grp_cmnts', $data);
}
view
foreach ($cmntlist as $cmnt):
echo $cmnt->comment . "<br>";
endforeach;
even though I set async: false in the ajax success function I can only get the last id(id of the last div) inside the ajax success function.but when i alert the id(id of the div) above the ajax part i am getting the correct id . so how can I pause the loop until ajax function finishes.sorry for my bad English please help me
Try to wrap your ajax call to immediately invoked function and pass id to it:
$('div#P_all_posts>div').each(function () {
id = this.id.replace("post", "");
(function(id) {
$.ajax({
url: 'http://localhost/seppro/index.php/group/show_comments',
type: 'post',
data: {
id: id
},
success: function (data) {
document.getElementById("cmnt" + id).innerHTML = data;
},
error: function (err, req) {
alert(err)
},
async: false
});
})(id)
});
It seems like your id var is global, and on each loop it rewrites its value, and by the time ajax is completed, id is equal to last value in loop.
The error seems to be in the fact that you never call the function show_comments() for first time in the the script
I recommend you to use this when you call it
setInterval(show_comments(), 5000)
And remove the setTimeOut() from show_comments()
Or you can just keep setTimeOut() and call show_comments() inside the script path or in the function you are going to call it

jquery date picker is not work when i put datepicker on ready after ajax call

I want to know that my jquery-ui datepicker is not working in document.ready after an ajax function call. when I put on ajax complete its work successfully please help what should I do. what's the reason for not working
$("#ScheduledArrivalDate").datepicker({
beforeShow: function () {
setTimeout(function () {
$('.ui-datepicker').css('z-index', 2000);
}, 0);
}
});
function getPage(page) {
$.ajax({
type: "POST",
url: page,
data: $("#frm").serialize(),
xhrFields: {
withCredentials: true
},
success: function (html) {
$('#List').empty();
$('#List').append($.parseHTML(html));
},
error: function () {
alert("error");
},
complete: function () {
alert("complete");
}
});
}
$.document.ready() only initiates after a page is loaded without ajax. When you replace/append html in an ajax call and you have a datefield in the new inserted html, you need to initialise it again (at least for the new inserted html block).
You could do this by calling $.datepicker in your success or complete function, like you already did, or by adding $.document.ajaxEnd() to your javascript file, what is initialized after every end of an ajax event (also on error).
Be aware not do double initiate the datepicker, especially when using ajaxEnd. This could lead to unexpected behaviour.
the code inside $(document).ready() will run only after page loads. While you are dynamically adding datepicker if I am not wrong. So do one thig. Take options in a variable like below:
var options = {
beforeShow: function () {
setTimeout(function () {
$('.ui-datepicker').css('z-index', 2000);
}, 0);
}
}
then:
$(document).ready(function(){
$("#ScheduledArrivalDate").datepicker(options);
});
and in ajax call:
function getPage(page) {
$.ajax({
type: "POST",
url: page,
data: $("#frm").serialize(),
xhrFields: {
withCredentials: true
},
success: function (html) {
$('#List').empty();
$('#List').append($.parseHTML(html));
$('#IdOfnewlyAddedDatePicker').datepicker(options);
},
error: function () {
alert("error");
},
complete: function () {
alert("complete");
}
});
}
Let me know if this not work or you are injecting html other than this.

What's wrong with my ajax function for fetching images?

I’m polling S3 every 5 seconds for an image. My polling is successful and I can see it GETs the URL with the image in web inspector. But the function inside of the done() isn’t executing (I can't see anything logging to console):
(function poll() {
setTimeout(function () {
userId = $('#photo').data('user-id');
photoPath = $('#photo').data('photo-path');
$.ajax({
type: 'GET',
dataType: 'json',
url: 'http://s3.amazonaws.com/my_bucket/user-photos/'+userId+'/original/'+photoPath,
done: function (data) {
console.log(data);
$("#photo").append(data);
},
complete: poll
});
}, 5000);
})();
What am I doing wrong?
You're asking for dataType: 'json' but you won't get that back because the server is sending an image.
Are you wanting to show the image in $('#photo')?
(function poll() {
setTimeout(function () {
console.log('polling');
userId = $('#photo').data('user-id');
photoPath = $('#photo').data('photo-path');
$('<img>').on('load', function(){
$('#photo').empty().append(this);
poll();
}).prop('src', 'http://s3.amazonaws.com/my_bucket/user-photos/'+userId+'/original/'+photoPath);
}, 5000);
})();
Demo (with image path replaced by jsfiddle logo)

How to use the timer in javascript?

I want to do the following application:
1) I want to retrieve the message using ajax. (Jquery)
2) When I read the message - I want to wait 10 seconds to retrieve the next message
3) Then wait another 10 seconds to retrieve the next message
4) All rows in a database.
How to use the timer in this case?
How can I start and then stop the timer?
function loadMessage(user_id)
{
$.post('ActionScripts/Message.php',{
user_id: user_id
}, function(data) {
//data
},"json");
}
function loadMessage(user_id)
{
$.post('ActionScripts/Message.php',{
user_id: user_id
}, function(data) {
//data
setTimeout(function(){loadMessage(user_id); }, 10000);
},"json");
}
I prefer calling the next ajax request after the completion of the previous (not as important with 10000 interval), but you do have to call the next one even if the first fails...
function loadMessage(user_id) {
$.ajax({
type: "POST",
url: 'ActionScripts/Message.php',
data: { user_id: user_id }
dataType: 'json',
async: true,
cache: false,
timeout:30000,
success: function(data){
// do what you need with the returned data...
setTimeout(function(){loadMessage(user_id); },10000);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
//do what you want with the error
setTimeout(function(){loadMessage(user_id); },10000);
}
});
}
The following implementation calls off to the server and executes every 10 seconds:
function loadmessage (user_id) {
$.post('ActionScripts/Message.php', {
user_id: user_id
}, function (data) {
//data
}, "json");
}
var interval = setInterval(function() { loadmessage(5345) }, 10000);
To stop the timer use clearInterval:
clearInterval(interval);
To restart the timer re-initialize the interval variable:
var interval = setInterval(function() { loadmessage(5345) }, 10000);

Categories

Resources