adding to array from inside ajax call javascript - undefined - javascript

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.

Related

AJAX: Store PHP data in a Javascript variable

As stated in the title, I have an ajax call. On the success function I want to store the returned data into a variable for use in my javascript. randNum.php simply returns a random number every 2 seconds, and I would like to use that number for other functions in my scripts. How can I use the data sent back from the php file in my javascript?
I know there are more logical ways to go about this, but want to know how to accomplish the task this way.
var result;
var interval = 2000;
function myCall() {
var request = $.ajax({
url: "randNum.php",
type: "GET",
dataType: "html",
success:function (msg) {
result = msg; //Not working as I intend
setTimeout(myCall, interval);
}
});
}
function(){
do something with result;
}
Declare a Global variable outside of the function and assign response variable to it after the ajax response.
var results;
function TestJSONP(){
$.ajax({
url: "randNum.php",
jsonp: "callback",
dataType: "jsonp",
success: function (response) {
console.log(response);
results = response;
}
});
}
You might not need to specify dataType, but use jqXHR.responseText to get the raw response. Something like
function myCall() {
var request = $.ajax({
url: "randNum.php",
type: "GET",
success:function (data, textStatus, jqXHR) {
result = jqXHR.responseText;
setTimeout(myCall, interval);
}
});
}
When you set dataType, and the response is not that type, then the ajax did not succeed and error call back will be invoked.

To get value from Json Object

In the below code i am passing json object it is in the format {"Table":[{"FAMin":0,"FAMax":40,"FAGrade":"C"}]}.How to get the value from it i tried the below code it results undefined .Pls help me to overcome this issue.
function UpdateGrade(GradeID) {
alert(GradeID);
$.ajax({
type: "POST", //HTTP method
url: "MarkorGradeSettings.aspx/GetGrade", //page/method name
data: "{'GradeID':'" + GradeID + "'}", //json to represent argument
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);// I get values
var parsedJson = jQuery.parseJSON(msg.d);
alert(parsedJson.Table.FAMin);//undefined
//handle the callback to handle response
if (msg != 'error') {
//$('#messages').addClass('alert alert-success').text(response);
// OP requested to close the modal
$('#myModal').modal('hide');
} else {
$('#messages').addClass('alert alert-danger').text(response);
}
//Now add the new items to the dropdown.
}
});
}
Table is an array but you are treating as an object
Try:
alert(msg.d.Table[0].FAMin)
Also as noted in comments there is no need to call jQuery.parseJSON when dataType:'json' is set. jQuery will parse the response internally and return object/array in callback
It looks like you missed that the data under Table is an array.
This should at least fix this particular case:
alert(parsedJson.Table[0].FAMin);

Save parsed JSON data into Variable [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I have this ajax request call to a json supported link (url1):
$.ajax({
type : "GET",
dataType : "json",
url : url1,
success: function (data) {
c1lat1 = [(data[0].boundingbox[0]),(data[0].boundingbox[2])];
alert(c1lat1);
}
});
This works perfectly fine, and the alert does give the number I want. However, if I try this:
$.ajax({
type : "GET",
dataType : "json",
url : url1,
success: function (data) {
c1lat1 = [(data[0].boundingbox[0]),(data[0].boundingbox[2])];
}
});
alert(c1lat1);
It gives me an empty alert box, and therefore it looks like it's not saving the value into the variable into the request.
How can I get around this as I need that value retrieved?
Thanks!
Since ajax is async by default, you have two options-
Alert the variable in the callback. You must proceed after you get the result in the callback-
$.ajax({
type : "GET",
dataType : "json",
url : url1,
success: function (data) {
c1lat1 = [(data[0].boundingbox[0]),(data[0].boundingbox[2])];
alert(c1lat1);
}
});
Make the call synchronous using async: false, this will make your call synchronous, and the control will come after $.ajax();
$.ajax({
type : "GET",
async: false,
dataType : "json",
url : url1,
success: function (data) {
c1lat1 = [(data[0].boundingbox[0]),(data[0].boundingbox[2])];
}
});
alert(c1lat1);
Reference
1) it's scope problems. c1lat1 inside success is local variable. Define it globaly.
2) success is async, so your alert happens before response from server, so no variable is set yet. move alert to success

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

Jquery post success variable scope

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.

Categories

Resources