Make Synchronous in ajax javascript - javascript

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.

Related

ajax looping settimeout, new request only after previous request is completed

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.

Jquery Ajax Callback not working in proper order

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
}

how to reset function into AJAX Response?

I have write the following code into AJAX to change the tab.
$("a").click(function(event){
if ($.browser.msie != true && $.browser.version != 8.0){
event.preventDefault();
if ($(this).parent().hasClass("current") == false){
$.ajax({
url: '/getvideofeed',
success: function(data) {
$('.flow').html(data);
cf._init();
},
data: {'playlistid': $(this).attr("pid")}
});
$(".current").removeClass("current");
console.log($(this).parent().addClass("current"));
}}
});
when i changed the TAB. the cf._init(); function getting called more than one time... means when i clicked 1st tab it will be called twice. when i clicked to next tab again cf._init() function will be called thrice and so on.
so my problem is how to reset cf._init() function after ajax called has been finished ? or how to called cf._init() function only once each time when i clicked any of the tab .
The function cf._init() should be executed on Ajax success
if cf._init() called more than once, than probably the Ajax is being performed more than once.
For start I suggest putting async property as follows:
async: false
so Ajax call will wait until it is finished.
This way will enable you to debug how come Ajax call is made more than once.
First make sure cf._init() is not calling ajax again ... 2nd why not call init when ajax is done or complete :
var request = $.ajax({"url":url});
request.done( function(data){ } );

stop executing another before one gets completed in jquery

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)
{
}
});

Calling a Javascript function after AJAX call

I have a javascript function to which I am being passed a functionName that I need to call after making a ajax call. The ajax call is returning some html that contains a reference to a js file. The functionName being passed to my function is in the html but it is referencing an object in the js file. What I am noticing that the object sometimes exists and sometimes doesn't. Is there a way to ensure that the object always exists(or wait till it exists) and then only call the javascript function. Please note that I have no idea what the object variable is, so is there a way to ensure that the script file has been loaded in dom and then make the call to the function.
function(functionName)
{
$.ajax({
url: properties.url,
type: properties.type,
data: properties.data,
dataType: properties.format,
success: function (data) {
// data contains <div>myname</div><script src="/myfile.js" type="text/javascript"></script>
// Put the data in some div
BindData(data);
// How to ensure that the script myfile.js is loaded in dom before I call eval
eval(functionName);
} );
}
function(functionName)
{
$.ajax({
url: properties.url,
type: properties.type,
data: properties.data,
dataType: properties.format,
success: function (data) {
// data contains <div>myname</div><script src="/myfile.js" type="text/javascript"></script>
// Put the data in some div
BindData(data);
//ensure the script has loaded.
$.getScript($('script:first',data).attr('src'), function(){
eval(functionName);
});
});
}
You can try to watch what is data before the ajax call end.
Not sure but, if data is "undefined" you can check something like this
var data = GetAjaxData();
while(typeof data === undefined);
bind, eval ecc ecc
But this will change if GetAjaxData return something else.
You can try the same thing but before do:
var data = null;
data = GetAjaxData();
while(data == null);
do stuff
You can also try $.ajax jquery with the success handler callback
Hope help

Categories

Resources