how to reset function into AJAX Response? - javascript

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

Related

unlike following queries first ajax query returns undefined

Have a bit of an issue here. I checked the different answers which seemed related to my problem but cannot seem to get this working.
I've got a page with a link like so :
View
And here's the javascript
var queryResult;
function getData(id, callbackfn){
$.ajax({
type:"POST",
url:"http://url/to/query",
data:{id: id },
success: function(data){
callbackfn(data);
},
error: function(){
return "err";
}
});
}
function showData(id){
getData(id, Callback);
if(queryResult)
{
alert("Yahoooooo !");
}
else
{
alert("Nope !!!");
}
}
function Callback(data){
queryResult = data.length;
}
When clicked for the first time the link launches the alert box and I get "Nope !!!" but any subsequent click will show a "Yahoooooo !"
If I reload the page then again "Nope !!!" for the first time and then it's fine afterwards. So it seems that queryResult is undefined on the first call but first call only. Any idea ?
Thanx
Put your control in Callback function
function Callback(data){
queryResult = data.length;
if(queryResult)
{
alert("Yahoooooo !");
}
else
{
alert("Nope !!!");
}
}
You're using .ajax
this method is asyncronous by default.
So you call "getData" then your Data is loaded.
While it is loaded you check if queryResult exists
Then the data has been loaded and your global flag is set
(At the moment you are checking if the previous request was successful)
The ajax call executes ansynchronously. Therefore when you call getData(), the method call returns instantly (and the ajax call is executing in another thread). This means the first time you click the link, there won't be anything in queryresult because the ajax call hasn't had time to finish before you hit your if block, but the subsequent times there (probably) will be, assuming the call has finished before the next time you click the link.
If you have any logic, such as that if block which depends on the data being returned from the ajax call, you must include it in (or call it from) your callback function.
So in this case you must move the block:
if(queryResult)
{
alert("Yahoooooo !");
}
else
{
alert("Nope !!!");
}
from the getData to the Callback function.

Why my setInterval function doesn't stop

I need to write a setInterval function in javascript. Thi is the code:
var myTimer=setInterval(function(){
var time=0;
$.ajax({
url:'...'
type: "POST",
dataType:"",
success: function (response) {
if(response=="true" || time>=10000){
clearInterval(myTimer);
}
time=time+1000;
},
error: function () {
alert("FAIL");
}
});
},1000);
I don't know why It doesn't stop in clearInterval. Anyone can help me?
You've claimed that the code does "come in the 'if'", so I assume the clearInterval call is actually being made.
Given that, the most likely explanation is that the interval is being cleared (after all, select isn't broken), but before the first "true" response, you've already made more than one ajax call, and the other ones you're seeing are ones scheduled before the interval was cleared.
E.g., your code runs and:
Fires off ajax call #1, which takes more than a second to complete
Fires off ajax call #2
Ajax call #1 completes but isn't "true"
Fires off ajax call #3
Ajax call #2 completes and is "true", clearing the interval
Ajax call #3 completes
Mixing two separate asynchronous intervals (one via setInterval and one via ajax) is asking for trouble.
If the goal is to make the request once a second and stop when you get back "true", I would have the success handler schedule the next call, e.g.:
(function() {
var time = 0;
var started = 0;
start();
function start() {
started = Date.now();
$.ajax({
url: '...'
type: "POST",
dataType: "",
success: function(response) {
if (response != "true") {
// Schedule the next call to occur one second after we
// started the previous call; or almost immediately if
// the call took more than a second to complete
setTimeout(start, Math.max(0, 1000 - (Date.now() - started)));
}
time = time + 1000;
},
error: function() {
alert("FAIL");
}
});
}
})();
Let me illustrate the expected and the actual scenarios to make things clearer.
Scenario #1
The image below shows the case where all your ajax requests complete before one second. You will notice that ajax callback success (or error) functions will execute only before clearInterval (which is what you always expect).
Scenario #2
When some of your ajax requests take more than one second (which is probably what happens), then your ajax callbacks can fire before / after / before-and-after the clearInterval, which makes you feel that your setInterval doesn't stop.
Note that your time variable is useless because it's a function-scoped variable that you initialize to 0 every function call. And even if it's a global variable, it'll only clear the interval in the 11th success function callback, and nothing guarantees how long these 11 successful requests will take.
Solution
As T.J. Crowder suggested, it's better to schedule the next ajax call in the success callback of the previous one, which guarantees that your ajax requests fire sequentially (only one at a time).
Note: Because you edited your question after his answer, then you'll also need to edit the if condition like this:
success: function(response) {
if (response != "true" && time < 10000) {
setTimeout(start, Math.max(0, 1000 - (Date.now() - started)));
}
}

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
}

Make Synchronous in ajax 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.

how to set and return a variable inside JavaScript function?

see the example first then you can understand my question.
var x;
function checkTime() {
$.ajax({
type: 'GET',
url: 'http://www.example.com/time.php',
data: test,
dataType:'json',
success: function (data) {
if (data == 0){
x = 'true';
} else if (data == 1){
x = 'false';
}
}
});
}
checkTime();
alert (x);
the alert will be undefined
I need to set x inside the checkTime functions and grab it outside the function
even if i do :
var x = checkTime();
alert (x);
i still get undefined
also i only need to check for true or false, maybe there is another way to do things. I also tried:
...
if (data == 0){
return true;
} else if (data == 1){
return false;
}
...
but i don't know how to check for that.
basically i need to so something like :
if (x == 1){ // if(x == true)
//do something
}
any ideas?
thanks
This happens because the default behaviour of .ajax() is asynchronous. x will not have been set by the time your alert() fires. You either need to set the .ajax() with aync=false or pass in a callback function to call when your Ajax request has completed, e.g.
function checkTime(callback) {
$.ajax({
type: 'GET',
url: 'http://www.example.com/time.php',
data: test,
dataType:'json',
success: function (data) {
var x = '';
if (data == 0){
x = 'true';
} else if (data == 1){
x = 'false';
}
// Call the callback function with 'x'
callback.call(null, x);
}
});
}
And then use it like follows:
checkTime(function (x) {
alert(x);
});
It happens because AJAX is asynchronous. When your code reaches alert, the success function of AJAX request does not executed yet. You can try to set ajax request to async:false, or make alert inside of success function.
You cannot directly access the return value of the function defined for the "success"; first you should know that two functions are involved here: checkTime, and the unnamed event handler function for the success event of the ajax call. You want to retrieve a value out of that unnamed event handler function; that function is however not called directly from checkTime, but when the AJAX request returns (it's event-driven programming: the function (data) {...} is executed when the event AJAX call succeeded happens).
In your example, the alert you call after executing checkTime will usually be called before the AJAX request is finished; this is because the AJAX request happens asynchronously, and therefore the event that the call succeeded need not have happened yet. If you always want to wait for the answer to the request, you can disable the asynchronicity of the AJAX call (async:false); but maybe you can also do the distinction what you want to do directly in the event handler instead of outside. That would be the way to go for if you want to follow event-driven programming paradigm.
If you want to continue doing something else while the request is running, your options would also include e.g. using some other (e.g. global) variable for the "return value" of the success function AJAX call (and possibly a second for indicating whether the call is finished), and checking periodically if it has been set yet (but that would not follow the event-driven programming paradigm, and might be considered bad practice since it unnecessary frequent polling of a variable is needed).
It happens because checkTime() returns immediately, before the success function is executed. The success function doesn't execute until after the ajax call is complete, so x is not set yet when you try to use it.
Depending on what you are trying to accomplish, you could put the alert inside the success callback.

Categories

Resources