Jquery post success variable scope - javascript

I'm trying to return the ajax success array from one function to another. For some reason I don't seem to be able to pass the data stored in a variable in the success part of the ajax function into the parent function to return.
I looked at this post to try and figure things out, but not such luck:
jQuery Ajax call - Set variable value on success
Thanks so much for any assistance.
Here's a simplified version of the code:
// make json_to_return global
var json_to_return;
function loop_through_data(){
// call the load_days function and put its array data into days_array
var days_data = load_days(03,2010);
// I'd like to be able to iterate through days_data here
//
//
}
function load_days(selectedMonth, selectedYear){
$.ajax({
type: "POST",
dataType: "json",
url: "../includes/get_availability.php",
data: "month=" + selectedMonth + "&year=" + selectedYear,
success: function(available_json){
json_to_return = available_json;
},
error: function(msg){
alert("error " + msg);
}
});
return json_to_return;
}

This part of your function happens later:
success: function(available_json){
json_to_return = available_json;
}
So the variable you're returning is undefined, because the code to set it doesn't happen until the response comes back from the server. Either call the rest of the code to run from your success function, so it'll run when the data's ready, or set async:false (less desirable because it locks the browser).
The async: false method is like this:
$.ajax({
type: "POST",
async: false,
dataType: "json",
url: "../includes/get_availability.php",
data: "month=" + selectedMonth + "&year=" + selectedYear,
success: function(available_json){
json_to_return = available_json;
},
error: function(msg){
alert("error " + msg);
}
});
The better approach:
$.ajax({
type: "POST",
dataType: "json",
url: "../includes/get_availability.php",
data: "month=" + selectedMonth + "&year=" + selectedYear,
success: function(available_json){
loopThroughTheDaysAndDoStuff(available_json);
},
error: function(msg){
alert("error " + msg);
}
});

$.ajax is an asynchronous function.
It means that when called, the function keeps executing.
In your code provided var days_data = load_days(03,2010); this happens:
Start an ajax call (asynchronous, function keeps executing)
return json_to_return (undefined)
days_data == undefined
ajax call finishes, json_to_return gets assigned (this can happen in any timespan)
You should rethink your logic, and start coding around the asynchronousity of the ajax call.
A first approach might be passing a function (callback) to load_days which should be called AFTER the success of the ajax call.

Related

Ajax call doesn't work without an alert call

Based on the flag 'isConformpage' we are adding some log in the database.
The log code is triggered via an AJAX call.
The flag condition is not being passed even though the value is 'true'.
It works if I add an alert() before the if condition.
PS: WriteLog1 method return in VB.net. Mentioning here although it doesn't have any impact on the question.
try {
setTimeout(function () {
//your code to be executed after 5 second
if (isconformpage) {
var split = document.getElementById("hdnconfirmpage").value.split("#");
transaction = split[0];
transaction = jQuery.parseJSON(transaction);
user = jQuery.parseJSON(split[1]);
component = jQuery.parseJSON(split[2]);
//Tagging log start
var pathurl = "/" + loc[1] + "/thankyou.aspx/WriteLog1";
$.ajax({
type: "POST",
url: pathurl,
data: '{Message: "' + "-" + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
// success: OnSuccess1,
failure: function (response) {}
});
// Tagging log end
}
}, 5000);
}
You are "Missing catch or finally after try"
Check https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch

Using two different ajax call

I have two different ajax calls . First one connects to one method of a web service . if it gets any null value for a specific field then it should call the other method from same web service . Here are the codes ..
$.ajax({
url: "webservices/ProdMonitorService.asmx/GetEstTimePrelimFinalCur",
data: "{'myactivity':'" + myactivity + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
async: true,
success: function (data) {
var obj = jQuery.parseJSON(data.d);
for (var i = 0; i <= obj.length - 1; i++) {
var dur_time_formated = '';
var mytimedur = obj[i].time_duration;
if (mytimedur != null) {
dur_time_formated = mytimedur.replace('.000000', '');
}
else {
//only one time check for this
$.ajax({
url: "webservices/ProdMonitorService.asmx/GetEstTimePrelimFinalCurTotalProcessing",
data: "{'myactivity':'" + myactivity + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
async: true,
success: function (data2) {
var obj2 = jQuery.parseJSON(data2.d);
dur_time_formated = obj2[0].total_processtime.replace('.000000', '');
}, error: function (result) {
//alert("Error: Please contact administrator for help: " + result.responseText);
}
});
}
For the first ajax call , it gets obj[0]......obj[7] but let say obj[0].time_duration comes null then it should go to second ajax call ,but even method "GetEstTimePrelimFinalCurTotalProcessing" returns some result , dur_time_formated varialbe comes null;, it is not even go thru second ajax call completely after first one.
Should use done function after first one is completed ?
You should try "async: false" instead of "async: true" here. This will work in your case.
bear in mind that ajax call is async. it means that dur_time_formated will be set later after your for-loop. so to solve the problem you can use any array variable outside your loop or sync ajax request

Declaring Variable within AJAX function and Calling It Later (jQuery) [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I've got an AJAX function that works correctly but I can't seem to access variables that I'm declaring within the function later in the page. If you look at the below code, you'll see I alert the variable number_rows within the function which works but when I try to log it outside of the function, it comes back as 'undefined.'
var newData = "user_id=" + id;
$.ajax({
type: 'POST', // HTTP method POST or GET
url: 'ajax.php', //Where to make Ajax calls
dataType:'text', // Data type, HTML, json etc.
data:newData, //post variables
success:function(response){
var number_rows = response;
alert(number_rows);
},
error:function (xhr, ajaxOptions, thrownError){
alert(xhr + " " + ajaxOptions + " " + thrownError); //throw any errors
}
});
console.log(number_rows);
I understand my scope may be off. I tried to move all of my code within the success function but that causing a bunch of other issues so the easiest thing would be to get the response variable to be a global variable that I could use throughout the rest of the page's code. I also tried something like this:
success:function(response){
$('body').append('<span class="ajax_response" id="' + response + '"></span>');
}
var number_rows = $('.ajax_response').attr('id');
console.log(number_rows);
But for some reason it isn't able to pick up the ID value immediately that way. I can confirm that the span does get made with the correct ID value but for some reason it doesn't handle it correctly. Any help with this would be greatly appreciated.
Thanks!
Just add to your configuration:
async:false
Your code maybe look like this:
var newData = "user_id=" + id;
var number_rows = ""; //This is a global variable
$.ajax({
type: 'POST',
url: 'ajax.php',
dataType:'text',
data:newData,
async:false, //<------This is the option you must add
success:function(response){
number_rows = response; //<----- receive data from the server
alert(number_rows);
},
error:function (/*stuff here*/){
//stuff here
}
});
//Check data
console.log(number_rows);
Good luck ^^!
Changed the scope of your variable.
Change async: false or wait till you get the response from server, then use the value.
var newData = "user_id=" + id;
var number_rows = ""; //Declare Here
$.ajax({
type: 'POST', // HTTP method POST or GET
url: 'ajax.php', //Where to make Ajax calls
dataType:'text', // Data type, HTML, json etc.
data:newData, //post variables
async: false,
success:function(response){
number_rows = response; //assign here
alert(number_rows);
},
error:function (xhr, ajaxOptions, thrownError){
alert(xhr + " " + ajaxOptions + " " + thrownError); //throw any errors
}
});
console.log(number_rows); //Use here
Yes, your scope is off. If you defining a variable inside a function, as you do, you cannot access it outside. Also your ajax call is async and any code you.
Put your console.log inside the success function otherwise it will probably log undefined even if you declare the variable globally outside of the function.
var newData = "user_id=" + id;
var number_rows;
$.ajax({
type: 'POST', // HTTP method POST or GET
url: 'ajax.php', //Where to make Ajax calls
dataType:'text', // Data type, HTML, json etc.
data:newData, //post variables
success:function(response){
number_rows = response;
alert(number_rows);
console.log(number_rows); // here, so we are sure it's set.
},
error:function (xhr, ajaxOptions, thrownError){
alert(xhr + " " + ajaxOptions + " " + thrownError); //throw any errors
}
});

adding to array from inside ajax call javascript - undefined

I declare an array then make an ajax call which returns multiple rows of values. I'm trying to add the id of these rows to that array that i declared previously, but it keeps returning undefined.
var recipeIds = Array();
$.ajax({
url: url,
type: 'POST',
contentType: "application/json",
dataType: 'jsonp',
crossDomain: true,
jsonp: 'jsoncallback',
cache:true,
success: function(data, status){
$.each(data, function(i,item){
recipeIds.push(item.id);
});
},
error: function(){
console.log("Ajax not working - recipies in cat");
}
});
alert("array0 = " + recipeIds[0]);
any suggestions?
When you alert, the ajax call hasn't yet returned. It's asynchronous, meaning the ajax call will happen after the alert.
You must use the result from inside the success callback you give to the ajax function.

javascript & jQuery scope question

I have the following method:
function priceRange(FESTIVALID){
jQuery.ajax({
url : '/actions/festheads.cfc?method=getPriceRangeByGUID',
type : 'POST',
data : 'FESTIVALID='+FESTIVALID,
dataType: 'json',
success : function(data) {
console.info("AJAX:qPrices",data.MINPRICE);
formatedPriceRange = '$ '+data.MINPRICE;
console.info("AJAX:formatedPriceRange", formatedPriceRange);
}//success
});//ajax;
//
return formatedPriceRange;
};
The second console.info correctly displays the formatedPriceRange,
but outside the function is undefined.
how can I access this variable out side the priceRange function?
Thanks
It's normal, that's how AJAX works. It's asynchronous, meaning that the jQuery.ajax function returns immediately and in this case formatedPriceRange hasn't yet been assigned a value and once the server responds (which can be for example 10 seconds later), the success callback is invoked and the variable is assigned a value.
So always consume the results of your AJAX requests inside the success callback function.
You also have the possibility to pass the async: false option to your jQuery.ajax call which will perform a synchronous request to the server and block until the result is retrieved. Obviously this will lead to your browser freezing during the execution of the request. So it would no longer be AJAX (Asynchronous Javascript And Xml) but SJAX (Synchronous Javascript and Xml).
You have to make sure that the AJAX request finishes before you access the price range data.
You need to expose the price range data outside the scope of the success function.
Here's how you can do it:
function priceRange(FESTIVALID, callback) {
jQuery.ajax({
url: '/actions/festheads.cfc?method=getPriceRangeByGUID',
type: 'POST',
data: 'FESTIVALID=' + FESTIVALID,
dataType: 'json',
success: function(data) {
console.info("AJAX:qPrices", data.MINPRICE);
formatedPriceRange = '$ ' + data.MINPRICE;
console.info("AJAX:formatedPriceRange", formatedPriceRange);
callback.call(this, formatedPriceRange);
} //success
}); //ajax;
}
var myFestivalID = 1;
priceRange(myFestivalID, function(priceRange) {
// this code runs when the ajax call is complete
alert('The formatted price range is:' + priceRange);
});
how can I access this variable out
side the priceRange function?
Like Darin said, you have to use your results in the success callback function.
Assuming you're using your current function like this:
var range = priceRange(festivalId);
// ... doing stuff with range variable
You'll want reorganize your code so that anything you do with the range variable stems from the success callback. For example, you can create a function to handle updating the UI with the new range:
function handleRangeVariabe(range) {
/// ... do stuff with range variable
}
Call it from success:
success: function(data) {
console.info("AJAX:qPrices",data.MINPRICE);
formatedPriceRange = '$ '+data.MINPRICE;
console.info("AJAX:formatedPriceRange", formatedPriceRange);
handleRangeVariable(formatedPriceRange);
}
Flower the steps of sample Code:
//declare function
function priceRange(FESTIVALID, functionCallBack){
//1º step
jQuery.ajax({
url : '/actions/festheads.cfc?method=getPriceRangeByGUID',
type : 'POST',
data : 'FESTIVALID='+FESTIVALID,
dataType: 'json',
success : function(data) {
//3º step, because this function will only trigger when server responds to request
//handle data in other function
functionCallBack(data);
}//success
});//ajax;
//more code
//2º step
//no return value, because this method no know when the data will return of server
//return formatedPriceRange;
};
var formatedPriceRange;
//using function
princeRange(1 , function(data){
console.info("AJAX:qPrices",data.MINPRICE);
formatedPriceRange = '$ '+data.MINPRICE;
console.info("AJAX:formatedPriceRange", formatedPriceRange);
});

Categories

Resources