Array doesn't keep content, maybe something with declaration [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I have an array declared in an else structure
var days = new Array();
$.ajax({
url: 'someurl',
dataType: 'jsonp',
success: processJSON
});
I process the data from the ajax call in the processJSON function
function processJSON(jsonData) {
var weather = jsonData.data.weather;
for(var key in weather) {
var day = weather[key];
days.push(new Array(day.tempMaxC, day.type));
}
}
I add some other arrays to the days-array.
If I check it in the console (in the processJSON-function), the length is three/
Then when I want to use the variable in some code under the the ajax-call, nothing works and when I check the length it's 0. I guess it's something with declaration?

Is your code under the Ajax call happening after the processJson function? The call to the ProcessJson function is asynchronous and happens only after the Ajax call finishes. However the code following it might happen before. So it might be a timing thing. If you need the array for any other processing you should have it in the callback or after you know the callback has been finished.

Put the declaration outside of the condition/else
var days = new Array();
if(...){
}else{
$.ajax
}

You need to wait until the XHR call has finished. It looks like you're using JQuery so check out their deferred docs (http://api.jquery.com/deferred.then).
You would end with something like this:
$.ajax({
url: 'someurl',
dataType: 'jsonp'
}).then(function( jsonData ) {
var weather = jsonData.data.weather;
for(var key in weather) {
var day = weather[key];
days.push(new Array(day.tempMaxC, day.type));
}
console.log( 'done!', days );
});

Related

Accessing an Array returned by a function in JavaScript [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I've got the following code:
$(document).ready(function() {
var blu = getData();
console.log(blu); //this shows full the array in the console
console.log(blu.length); //this gives back 0
});
With the following function getData()
function getData() {
var arr = [];
var json;
$.ajax({
url: "someurl.com",
dataType: 'json',
data: json,
success: function(json) {
var x = json.somejson.somenumericvalue //gets the amount of dataentries
for (i = 0; i <= x - 1; i++) {
arr.push(json.feeds[i].field1); // fill up array with the values from the json feed
}
} //end of success function
}); //end of ajax
console.log(arr.length) //shows the correct length of the array
return arr;
} //end of function getData
Problem is I want to access the values and do methods (like .length) with the array which is filled in the function but it somehow does not work. Anyone can help out?
Cheers.
You can use $.each or for in loop
E.g.
$.each(Blu, function (i, v){//do whatever with array values, i: index, v: value}
Or
For(i in Blu){//i: index, access your value by Blu[I] & do whatever with your value}
Hope it'll help you out
The json data returned by the ajax call must be accessed by object notation if it is a named array. To retrieve the length of such an data object use:
Object.keys(data.datanode).length
It is not clear what your json looks like, you probably need to iterate through it. Assuming that you want to iterate through json.feeds:
function getData(){
var arr = [];
var json;
$.ajax({
url: "someurl.com",
dataType: 'json',
data: json,
success: function(json){
for(var i in json.feeds) {
arr.push(json.feeds[i].field1); // fill up array with the values from the json feed
}
console.log(arr.length)//shows the correct length of the array
return arr;
} //end of success function
}); //end of ajax
}//end of function getData
Also note where console.log and return is. I would suggest reading a basic book about javascript, specifically closures and variable scope. That's why your code doesn't work and the problem is not in ajax, json, or object iterating.

Extracting Array - undefined [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I have an ajax getting values from db, and the result is pushed into an array:
function pushPONFail(dt, ct) {
if (ct < 12) {
var tMon = parseInt(dt.getMonth())+1;
var tYear = dt.getFullYear();
ct++;
} else {
return;
}
data = {"qType": 101,
"tbl": 'qualitypqa.dbo.centerthickness',
"month": tMon,
"year": tYear,
"type": 'Lotrafilcon B'};
$.ajax({
cache : false,
url: "getrpt.php",
type: "get",
data: data,
contentType: 'application/json; charset=utf-8',
async: true,
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("error: "+textStatus+" : "+errorThrown);
}
})
.done(function(response){
var obj = jQuery.parseJSON(JSON.stringify(response));
arrPONFail.push({Month: months[tMon-1]+"/"+tYear, PONFail: obj[0].PONFail});
dt = new Date(dt.setMonth(parseInt(dt.getMonth()) - 1));
pushPONFail(dt, ct);
});
} // pushing values such as ["May/2017", 0]
$(function() {
var dt = new Date();
pushPONFail(dt, 0);
console.log(arrPONFail);
});
These are the complete function. When I console.log the array, it came out as my picture. I'm unable to extract the data.
When I print the array into the console, it came out as the picture below.
How do I get the values back out from the array?
When I do an arrT[0], I get an undefined.
Please advise.
This is most likely an asynchronous issue - are you accessing arrT[0] outside of the .done() function? If so, at the time you're accessing it, there is nothing in the array - it's empty. The ajax request you're making takes some time (milliseconds), and only after that data returns does your array have something in it. To use the values in the array, try putting the code that uses the array inside the .done() function itself.

JQuery - force multiple ajax requests to run in sequence [duplicate]

This question already has answers here:
Make jQuery ajax calls in order
(2 answers)
Closed 5 years ago.
The following executes each ajax call using jQuery in sequence. The calls must be in sequence. The only way I've found this works is by using async: false, which I know is deprecated and should not be used. The code below loops through each element in the [name] array and fires each ajax request in sequence. When I remove async: false, the ajax calls are made out of sequence and sometimes one of them does not seem to fire at all. I thought ajaxComplete might help me here but I've had no luck. Is there a way to make these ajax calls fire in sequence?
function doGetJson(name1) {
var URL = 'http://some url/?name=' + name1;
$.ajax({
url : URL,
dataType : 'jsonp',
async: false,
jsonpCallback : 'getJson',
name: name1,
index: i,
success : handleJson
});
};
function handleJson(data) {
<...some other operations...>
};
var name = "test1,test2,test3".split(",");
for (var i = 0; i < name.length ; i++ )
{
doGetJson(name[i]);
}
You should make use of promises. First let your function return the $.ajax like so:
function doGetJson(name1) {
var URL = 'http://some url/?name=' + name1;
// notice the return !!!
return $.ajax({
url : URL,
dataType : 'jsonp',
async: false,
jsonpCallback : 'getJson',
name: name1,
index: i,
success : handleJson
});
};
Then you chain them like that:
var name = "test1,test2,test3".split(",");
var promise = name.slice(1)
.reduce( (a,b) => a.then(doGetJson.bind(null, b))
, doGetJson(name[0]) )
promise.then(function(){
// do something when all requests are ready
})

jquery : constructed data is undefined [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I spent lot of time to figure this out but did not find anything,
function constructAgenciesData() {
$.ajax({
url: "getAgenciesAndGlobalJson.do",
dataType: "json",
success: function(data){
$.each(data, function (index, row) {
// console.log("data : "+ JSON.stringify(data));
$("#"+row.id).data("assignedAgencies", row.assignedAgencies).data("restOfAgencies", row.restOfAgencies).data("global", row.global).data("globalID", row.globalID);
});
}
});
}
constructAgenciesData();
$(function($){
$(".globalswitch").each(function () {
var idRow = $(this).parents('tr')[0].id;
alert(idRow);
console.log($('#'+idRow).data("global"));// <-- UNDEFINED
$(this).switchButton({
checked: row.data("global")
});
});
$(document).on('click','button.btn', function () {
var idRow = $(this).parents('tr')[0].id;
var title = $(this).parents('td:first').siblings(':eq(1)').text();
title = "Rule Name : " + title;
$("#divPopUp").data('param_1', idRow);
$("#divPopUp").data('opener', this).dialog("option", "title", title).dialog("open");
console.log($('#'+idRow).data("global"));// <-- WORKING
var old_array = $('#'+idRow).data("restOfAgencies");
var new_array = $('#'+idRow).data("assignedAgencies");
addCheckbox(diff(old_array,new_array));
});
});
I don't know why the same line :
console.log($('#'+idRow).data("global"));
is undefined in the .each function.
BUT it is working in the click function .
Your $.ajax call is asynchronous. This means that it is firing request while the rest of the Javascript is being run.
The success function within constructAgenciesData() might not have been completed prior to the IIFE $(function($){.
Therefore, there is no guarantee that the .data('global') will be set by the time you're trying to access it within the $(".globalswitch").each loop.
A solution to this issue would be to wrap the $(".globalswitch").each loop within a function globalSwitchLoop() and fire that on the success of the $.ajax call.
Also, take a look at jQuery's promises.

jquery ajax gets HTML but will not return it [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to return the response from an AJAX call from a function?
I'm trying to get some HTML content via ajax. But for some reason, though the HTML makes it to the ajax function, when I try to use it as a returned value, I get undefined.
Like this:
function get_additional_options(name) {
var post = $.ajax({
type: 'post',
url: 'order_queries_templates/html/' + name + '_additional_options.php?<?=time()?>',
//data:'product_id=' + product_id,
dataType: 'html'
});
post.done(function (p) {
console.log(p); //prints out all the HTML just as I would expect
return p;
});
}
but when I try to get the HTML to append it to my page like this
if (has_additional_options == "t"){
var html_to_append = get_additional_options(name);
console.log(html_to_append); // undefined
}
It is the same result if I use the done() method, or just return the value as a success callback. What is my error?
You can't return values from asynchronously called functions.
You should return post (i.e. the result of $.ajax) and then register a .done handler outside of your function:
function get_additional_options(name) {
return $.ajax({
...
});
};
if (has_additional_options == "t") {
get_additional_options(name).done(function(p) {
console.log(p);
});
// NB: code execution continues here immediately - don't do anything
// else here - all further stuff must be done in the above callback
}
You are returning the HTML value inside the anonymous function.
You're basically passing it to the post.done method.
Maybe it's better to use events in this case since you're running asynchronous code here.
function get_additional_options(name) {
var post = $.ajax({
type: 'post',
url: 'order_queries_templates/html/' + name + '_additional_options.php?<?=time()?>',
//data:'product_id=' + product_id,
dataType: 'html'
});
post.done(function (p) {
$("body").trigger("html_loaded",[p]);
);
}
$("body").on("html_loaded", function (htmlData) {
// Do something with your HTML data here.
$(this).append(htmlData);
});

Categories