am trying to call an ajax function several times to fetch data from my chat table, and appending the data into the div only if there are new messages in that table.
my code
(function CallThat() {
$.ajax({
url:'intervalog.php',
method:'POST',
data:{datime:mylmsgt},
success:function(data){
if(data!=5){
$('#intrmylmsgt').load('intrmylmsgt.php');
$('#chatlogs').append(data);
}
}
});
setTimeout(CallThat, 1000);
}());
this works perfect only for 10-15 seconds, after that it starts giving these errors continuously in console (jquery.min.js)
POST http://******/intervalog.php 0 ()
after that page stuck and i have to close that page.
I think the problem is continues ajax request without completing the previous requests, any solutions?
you should use async: false to make ajax work synchronously
(function CallThat() {
$.ajax({
url:'intervalog.php',
method:'POST',
data:{datime:mylmsgt},
success:function(data){
if(data!=5){
$('#intrmylmsgt').load('intrmylmsgt.php');
$('#chatlogs').append(data);
CallThat()
}
}
});
}());
and check CallThat() function for empty,null responses . if response is coming empty or null then don't call CallThat() next time.
Related
I have a script that runs a long conversion php script and a progress polling script. After looking at several posts about this subject i found that it should be possible to use async ajax calls combined with timeout from javascript to create a construction that would poll the progress regularly and update my page with a percentile number. See code below
function startExcelConversion(excelname){
var poll = function(){
setTimeout(function(){
$.ajax({
url: "../include/ajax/ajax.php?action=poll_progress",
success: function(data){
//Update the progress bar
// show progress
console.log('progresser: '+data);
$("#progress").val(data);
//Setup the next poll recursively
poll();
},
complete: function( jqXHR, textStatus ){
//Update the progress bar
// show progress
console.log(textStatus);
},
dataType: "json"
});
}, 3000);
};
poll();
//show loading image
console.log('starting conversion');
$('#progress').val("Excel openen...");
$('#main').prepend('<img id="loading" src="../include/image/load.gif">');
$("#loading").show();
$.ajax({
url: '../import/import_main.php?clean&action=importexcel&excelname='+excelname,
success: function(data) {
console.log(data);
$("#main").html(data)
$('#loading').hide();
}
});
return false;
}
the first block launches the script that runs a while (excel reading and conversion).This script updates a database table every 10 rows to set the progress. the second block (from start polling onwards0 should launch a php script that reads this progress db field and echo it so i can update my input field with the percentile. However the polling script is not called during the runtime of the first php script (import_main.php). I tried $.post and $.get calls (which should as $.ajax be asynchronous by default). Also tried setInterval but that did not work and was not recommended due to timing problems. Am i missing something obvious here or is it a setting in php i am missing?
thnx in advance
I would try to define poll at the top of the script, like:
var poll = function(){
setTimeout(function(){
$.ajax({
url: "../include/ajax/ajax.php?action=poll_progress",
success: function(data){
//Update the progress bar
// show progress
console.log('progresser: '+data);
$("#progress").val(data);
//Setup the next poll recursively
poll();
},
dataType: "json"
});
}, 3000);
});
and then call it, like, poll(), after the ajax call. See if that helps. Right now, you have an anonymous function after the ajax call, but it tries to call itself with poll(); in the success callback, which isn't going to be defined.
it turned out the problem was threefold:
The first problem was indeed the use of an IIFE function that was not defined at runtime. So using inline function such as z416175 described was certainly valid
The second problem was that when a session is active in PHP it will block other (ajax) calls to prevent session overwriting. So using session_write_close() before entering the long running script worked to allow asynchronous ajax calls for progress updating. See this post (thnx to z416175) One ajax call block other ajax call
The third problem was that when you use xdebug the second problem remains because xdebug keeps a session open preventing the asynchronous ajax progress update call. So be aware when testing that xdebug causes problems with this
Thanks for all input. I have credited z416175's post for various usefull info in his answer and comments
I have a piece of code I want to run after all the ajax is completed.
The function I wish to run is:
function autoContinueCart(){
$('.nextSection a:visible').click();
}
This click event runs validating script and moves to next section. Heres the main ajax.
$('#SubmitLoginOpc').click(function () {
$.ajax({
type:'POST',
url:authenticationUrl,
async:false,
cache:false,
dataType:"json",
data:'SubmitLogin=true&ajax=true&email=' + encodeURIComponent($('#login_email').val()) + '&passwd=' + encodeURIComponent($('#login_passwd').val()) + '&token=' + static_token,
success:function (jsonData) {
if (jsonData.hasError) {
//error stuff
}
else {
// update token
static_token = jsonData.token;
$('#dlv_label, #new_label').removeClass('new-l').addClass('logged-l'); // change label on delivery address section
updateNewAccountToAddressBlock();
// RESET ERROR(S) MESSAGE(S)
$('#opc_account_errors').html('').hide();
$('#opc_account_errors_invoice').html('').hide();
//It doesnt work here
//autoContinueCart();
}
},
//doesnt work here
// complete:autoContinueCart
});
return false;
});
I have put this function call in the success part, which I thought would work since it is synchronous. I also put it as complete and in .done function after the ajax call and it still runs before all the inside code is complete. The function updateNewAccountToAddressBlock(); basically makes another jquery ajax request with this type async:true, and returns json that is then used in about 10 functions or sub functions in the success call. One of these uses this data to fill out all the fields of a form. My function I am trying to call at the end is supposed to validate the info that is being populated. But no matter what I try, the validation is failing because the autoContineCart is being run before the fields are being populated. I also tried to use a callback like updateNewAccountToAddressBlock(updateAddressSelection); and then checked callback function inside of that and it also didnt work. Anyone have an idea what I could be doing wrong?
Since your call is already asynchronous, is it possible to move the processing code out of the ajax callback function? This would ensure that all of the ajax portion is complete before moving on to the processing piece.
Example:
$('#SubmitLoginOpc').click(function () {
$.ajax({
type:'POST',
url:authenticationUrl,
async:false,
cache:false,
dataType:"json",
data:'SubmitLogin=true&ajax=true&email=' + encodeURIComponent($('#login_email').val()) + '&passwd=' + encodeURIComponent($('#login_passwd').val()) + '&token=' + static_token
},
success: function(jsonData) {
$('#SubmitLoginOpc').data("some_key",jsonData);
}
//doesnt work here
// complete:autoContinueCart
});
jsonData = $('#SubmitLoginOpc').data("some_key");
if (jsonData.hasError) {
//error stuff
}
else {
// update token
static_token = jsonData.token;
$('#dlv_label, #new_label').removeClass('new-l').addClass('logged-l'); // change label on delivery address section
updateNewAccountToAddressBlock();
// RESET ERROR(S) MESSAGE(S)
$('#opc_account_errors').html('').hide();
$('#opc_account_errors_invoice').html('').hide();
//It doesnt work here
//autoContinueCart();
return false;
}
});
As the poster above said, Perhaps you could move some of the other ajax functions to run from the same js file, or move some of the Php functions to be run at the same time as the first call.
Ideally you shouldn't have to do another ajax request, because the php/whatever already has the info it needs from the client side. You should be able to send that data to other php/whatever scripts.
If you do need to do another ajax call, perhaps having the user wait a mandatory second, before you run the ajax call.
for instance:
$ajax.done(
// code
if (success)
{
setTimeout('foo', 5000);
$('#spinner').show();
}
function foo()
{
$('#spinner').hide();
//second ajax request
}
I am using $.ajax inside the for loop in jquery.
for(var i=0; i < 2; 1++)
{
$.ajax({
url :"/models/getdata"+i
dataType:"json"
success:function(data)
{
}
});
}
before going success function for i=0; i=1 comes and performing the ajax request for this value. i want next iteration need to wait until current one gets completed.
that means one ajax request successfully completed and then it will increment the i value then start the next iteration.
consider another scenario also
function A()
{
$.ajax code
}
/////another operation
same here function A() need to wait until its ajax post get completed. but in my case it goes to next code start executing how can i stop further execution before current function gets completed. like sleep concept in C#
how can i do this ?
Thanks,
Siva
A simple generic solution :
var i=0;
(function doOne(){
$.ajax({
url :"/models/getdata"+i
dataType:"json"
success:function(data){
if (++i<2) doOne();
}
});
})();
For your second case, you may use the deferred returned by $.ajax :
function A() {
return $.ajax(...)
}
A().done(function(){
// some code executed after the ajax call finished
});
set async: false in the ajax call
This method could be the best way to handle this problem.
$.when(*AJAX CALL*)
.then(function() { // Function to run after ajax is completed
});
By default, all requests are sent asynchronously when we use $.ajax. By asynchronously, I meant, web applications can send data to, and retrieve data from, a server (in the background) without interfering with the display and behavior of the existing page. But you want execution to be stopped until your request is complete so set async to 'false'.
Use this -
$.ajax({
url :"/models/getdata"+i
dataType:"json",
async: false,
success:function(data)
{
}
});
There is a page and I want periodically to make "background" ajax requests. So the page is loaded then it should send ajax requests in a certain amount of time.
I might use cron for that. I have never use previously so I'm wondering if it would fit for that task. Is there any other more simple way?
P.S. The time delay will be about 5 minutes.
Since there is essentially an unknown delay between the time you send out an AJAX request and the time you receive a complete response for it, an oftentimes more elegant approach is to start the next AJAX call a fixed amount of time after the prior one finishes. This way, you can also ensure that your calls don't overlap.
var set_delay = 5000,
callout = function () {
$.ajax({
/* blah */
})
.done(function (response) {
// update the page
})
.always(function () {
setTimeout(callout, set_delay);
});
};
// initial call
callout();
Cron is run on the serverside and you are using HTML and AJAX, so you should solve this issue in Javascript :-)
By using something like setInterval you can keep executing a function, your case might be something like polling a url via AJAX:
function updatePage(){
// perform AJAX request
}
setInterval(updatePage, 5000);
Depending on your rails version you may be able to use periodically_call_remote, otherwise you'll need the jquery alternative that #Bitterzoet described.
More info in this question.
You can send ajax request in four second like this:
setInterval(get_news, 4000);
function get_news(){
$.ajax('/dashboards/get_news', {
type: 'POST',
success: function(result) {
if(result > 0){
$('#div_1').text("See "+result+" new messages");
$('#div_1').show();
}
else{
$('#div_1').css('display', 'none');
}
},
error: function() {
// alert("Error")
}
});
}
Are you using jquery? If so, you can implement this method:
// first, you need asing a callback timer
var timeout = 300; //milliseconds
// this method contain your ajax request
function ajaxRequest() { //function to ajax request
$.ajax({
url: "/url/to/request/"
}).done(function(data) {
alert("response is: " + data);
});
}
$(document).on("ready", function(){
//this method will be called every 300 milliseconds
setInterval(ajaxRequest, timeout);
});
in my script i have an ajax call to a php file and i would like to have the call completed before the rest of the script below gets executed
Here is the script i am referring to:
function game_settings(state){
if(state == "load"){
ui.load_game();
//do ajax call to load user last save
var dataString = {"user_data": "true"};
$.ajax({
type:"POST",
url:"PHP/class.ajax.php",
data: dataString,
dataType: 'JSON',
success: function(success) {
player_details_init(success)
},
error: function(){
alert("ERROR in User data");
}
});
console.log (player_level);
//scene.load("level_"+level);
//instantiate a heroObject
player = new Player(20,20,game_width, game_height);
// set it's image to the proper src URL
player.image.src = "images/Mage_Sprite.png";
// once the image has completed loading, render it to the screen
player.image.onload = function()
{
player.render();
};
lastUpdate = Date.now();
}
SO for instance right now when the script runs, i can see in console that the ajax request gets made, and then the rest of the script gets execute before the ajax has finished resulting in this call:
console.log (player_level);
to return undefined rather then the value it should be because the ajax hasn't completed.
To clarify my question is:
How should i make the ajax call finish before the rest of the script gets processed?
Thanks
Put the "rest of the script" inside the success callback function.
You can either put the rest of the script in the success callback of the AJAX call, or set the async property of the AJAX call config to false, which will make it synchronous.