JS Array values become undefined [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I have a function that pull information from an XML file located on the system. IT will then pull the values located in that file and put them into an array. Once the function is called the values enter the array, but then onnce the function ends the values go away.
function getXML(location,day){
$(document).ready(function () {
$.ajax({
type:'post', //just for ECHO
dataType: "xml", // type of file you are trying to read
crossDomain:true,
url: './../CurrentFiles/'+ location +'.xml', // name of file you want to parse
success: function (xmldata){
if(array[0] == null){
$(xmldata).find('dgauges').children().each(function(){
array.push($(this).text());
});
}
}, // name of the function to call upon success
error: function(xhr, status, error) {
console.log(error);
console.log(status);
}
});
});
return array[day];
}
From what I researched it could be a problem with async, but I do not understand entirely what that is.
Also I am very new to jquery so if there is any thing that seems out of place that's why.
THis is what my plan is for this function
I have an XML file formatted like
<dgages><d>26.850</d><d-1>7.70</d-1><d-2>2.00</d-2><d-3>27.90</d-3></dgages>
I am trying to pull all of those values in an array so I can do some calculations on them.
Get the XML Document
find all the children of dgage
put each of the children into the array
4 once the array is filled return the associated day.

Try making a synchronous call instead. AJAX calls are async by default, which means that code will jump to the next line before waiting for the result of the previous line. You can enforce the result by telling the AJAX call to do it synchoronously:
function getXML(location, day) {
var array = [];
$.ajax({
type: 'post', //just for ECHO
dataType: "xml", // type of file you are trying to read
crossDomain: true,
async: false, // Wait until AJAX call is completed
url: './../CurrentFiles/' + location + '.xml', // name of file you want to parse
success: function(xmldata) {
if (array[0] == null) {
$(xmldata).find('dgauges').children().each(function() {
array.push($(this).text());
});
}
}, // name of the function to call upon success
error: function(xhr, status, error) {
console.log(error);
console.log(status);
}
});
return array[day];
}

Related

shift() and pop() is not a function

So i was making a random quote generator machine project for learning purposes and encountered a error.
I tried looking for it in other answers but couldn't understand/solve it.
here is the JS code:
$('#new').on('click', function(e) {
e.preventDefault();
$.ajax( {
url: 'https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&_jsonp=mycallback',
success: function(data) {
console.log(data);
var post = data.shift(); // The data is an array of posts. Grabbing the first one.
$('.author').text(post.title);
console.log(post.title);
$('.quote').html(post.content);
console.log(post.content);
},
cache: false
});
});
For the first console.log it shows data in form of array, So I tried pop and shift functions to extract the data. here is the format of data:
/**/mycallback([{"ID":1640,"title":"Scott Belsky","content":"<p>To envision what will be, you must remove yourself from the constant concern for what already is.<\/p>\n","link":"https:\/\/quotesondesign.com\/scott-belsky\/","custom_meta":{"Source":"<a href=\"http:\/\/the99percent.com\/book\">book<\/a>"}}])
It gave undefined for the next 2 console.log() .
Here is the error:
Uncaught TypeError: data.shift is not a function
and it gave errors on both functions. any help would be appreciated.
Two things:
Don't define the callback function. Leave that to $.ajax by replacing the explicit function name to ?
Set the data type to jsonp
$.ajax( {
url: 'https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&_jsonp=?',
dataType:'jsonp',
cache: false,
success: function(data) {
console.log(data);
var post = data.shift();
console.log(post);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>

Synchronous POSTing to SQL handle using AJAX [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I wish to make a synchronous call to a page that handles SQL insert of the words I'm posting. However since I have many chunks and SQL is not asynchronous I wish to process each ajax call/chunk after another
for (chunk = 1; chunk <= totalchunks; chunk++) {
$.ajax({
type: "POST",
dataType: "json",
url: "updateHandle.php",
data: {words:arr.slice(1000*(chunk-1),1000*chunk),push:getpush},
success: function(){
console.log('Items added');
},
error: function(){
console.log('Errors happened');
}
});
}
the
async: false,
does not work for some reason. Each ajax call always goes to the error case and not the success case. So is there another solution to this issue that I've overlooked?
I thought about using a busy-waiting while-loop and use locks, but the setTimeout() function does not work as expected (probably some error on my part)
EDIT: The chunks are too big for one AJAX call hence serialization is needed. Also the amount of chunks may change from call to call, so flexibility is needed.
How about something like:
function insertWords(words){
if(words.length) {
$.ajax({
type: "POST",
dataType: "json",
url: "updateHandle.php",
data: {
words: words.splice(0, 1000),
push: getpush
},
success: function(){
console.log('1000 items added');
insertWords(words);
},
error: function(){
console.log('Errors happened');
return;
}
});
} else {
console.log("Done inserting all words.")
}
}
You can use a callback as a param of insertWords or return a promise to make it even more resilient.

Get resultfrom AJAX call into javascript 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 been trying to find a solution to this for a while now but i can not seem to get it to work.
What i am doing:
I am trying to get a array from my php file so i can use it in my javascript.
Example.php
$arr = Array(
Array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0),
Array(1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0),
Array(0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0),
Array(0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0),
Array(0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0),
Array(0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0),
Array(3,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0),
Array(3,3,3,3,3,3,0,0,0,0,1,0,0,0,0,0,3,3,3,3,3,0,0,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0),
Array(0,3,3,3,3,3,3,0,0,0,1,0,0,0,3,3,3,3,3,0,0,0,0,0,3,3,0,1,1,1,1,1,1,1,0,0,0,0,0,0),
Array(0,0,0,0,0,0,3,3,3,3,1,3,3,3,3,3,0,0,0,0,0,0,0,0,0,3,3,1,3,3,3,3,3,1,1,1,1,0,0,0),
Array(0,0,0,0,0,0,0,3,3,3,1,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,3,1,3,3,3,3,3,3,3,3,1,0,0,0),
Array(0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,3,3,3,1,1,0,0),
Array(0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,3,3,1,1,1),
Array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,1,1,3,3,3,3,3,3,3),
Array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,3,3,3,3,3,3,3,3),
Array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,3,3,3,3,3,3,3,3),
Array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,1,3,3,3,3,3,3,3,3),
Array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,1,3,3,3,3,3,3,3,3,3),
Array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,1,3,3,3,3,3,3,3,3,3,3),
Array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,3,3,3,3,3,3,3,3,3,3)
);
echo json_encode($arr);
And i am calling this with a javascript function
function getArray(){
$.ajax({
url: 'Example.php',
success: function(resultarray) {
alert("success " + resultarray);
return levelarray;
},
error: function(xhr, status, error) {
//alert(xhr.responseText);
}
});
}
This alert("success " + resultarray); does return the array like it should.
But when i want to use it in my javascript it keeps saying it is undefined, or it does not say anything.
I tried it like this:
var test = getArray();
alert("result= "+ test);
So this Alert keeps returning me errors or empty values.
Does anyone know how i can do this?
Thank you in advance.
This is related to the asynchronous nature of javascript. Instead of using your function like
var test = getArray();
Try something along the lines of
function getArray(){
$.ajax({
url: 'Example.php',
success: function(resultarray) {
alert("success " + resultarray);
doSomethingWithMyTiles(resultarray);
},
error: function(xhr, status, error) {
//alert(xhr.responseText);
}
});
}
with
function doSomethingWithMyTiles(resultarray){
//do stuff
}
if you want to use the success result in another js function, put that function inside the success() of the ajax. ajax runs asynchronous, so it doesnt run in sequential order with other functions. just do something like:
$.ajax({
url: 'Example.php',
success: function(data) {
// myFunction(), do something here with data from ajax;
},
});

AJAX response into an object [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 a stringified array of objects in a database that I'm retreiving with an $.ajax call. I'm trying to use a callback function to get that data into an array outside of my ajax function.
function getMap(){
return $.ajax({
url: "getMap.php",
type: "POST",
data: "",
dataType: 'JSON',
success: dataHandler
});
};
function dataHandler(data){
console.log(JSON.parse(data));
return JSON.parse(data);
}
var loadedMap = getMap();
console.log(loadedMap);
The console.log inside of the dataHandler function shows up in my Javascript console as a standard Array (clickable, can view all the data). The console.log at the very end shows up in the console as [object Object]. I can see the actual data inside of that object in a "responseJSON" field, but I can't seem to correctly get that into the loadedMap array.
What am I missing here?
Edit: I feel like my question is different from all of the answers to other questions. Mine seems to be more of a scope problem. A lot of the answers advocated the .done and .fail ways to handle AJAX.
var loadedMap = [];
function getMap(){
return $.ajax({
url: "getMap.php",
type: "POST",
dataType: 'JSON',
});
};
getMap().done(function(r) {
if (r) {
loadedMap = r;
} else {
console.log("No data");
}
}).fail(function(x) {
console.log("error");
});
console.log(loadedMap);
This code successfully gets the array where "loadedMap = r", but when you console.log the loadedMap on the outside, its undefined. How can we get the actual data to be outside the AJAX functions?
The function getMap does not return the response, it just calls dataHandler when the response arrives.
create a global variable and assign the vallue of the JSON.parse(data) to that variable. :
var myData;
function getMap(){
...
});
};
function dataHandler(data){
console.log(JSON.parse(data));
myData = JSON.parse(data);
}
getMap();
JQuery's AJAX returns a promise, so you can either go the callback route, as it looks like you were trying to do, or you can simplify it with promises:
function getMap(){
return $.ajax({
url: "getMap.php",
type: "POST",
data: "",
dataType: 'JSON',
success: dataHandler
});
};
getMap().then(function(data){
loadedMap = JSON.parse(data);
console.log(loadedMap);
});

Load data asynchron in a JS object [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I'm currently writing a JS class for my webshop application to access product information which is stored on the server. The information should be loaded asynchronously. For this I use dojo.xhrPost(). I want to rewrite a function for this class, called getProductName(productId:int):String which returns the product name for a given product id. The function uses intern dojo.xhrPost(). But whould should I return the loaded product name due to the fact that I have to pass new function to load and error in dojo.xhrPost()?
Usage of this function: Other JS functions call this to load the product name to update the cart webpage without reloading the whole page. The data returned is in JSON format due to the fact that some additional information is transferred for error handling (the client function has to know if any error occurred on server-side or not).
The code for the function getProductName(productId:int):
function getProductName(productId) {
dojo.xhrPost({
url: '/shop/dataProduct.php',
handleAs: 'json',
content: {productId:productId},
load: function(response, ioArgs) {
if (!response.error) {
// here I would like to return response.data to the caller of myObj.getProductName(productId)
} else {
// here I would like to return "error" to the caller of myObj.getProductName(productId)
}
return response;
},
error: function(response, ioArgs) {
// here I would like to return "error" to the caller of myObj.getProductName(productId)
return response;
}
});
}
The usage:
var productName = myObj.getProductName(5);
The problem with the following line of code is that it is assuming the the retrieval of the product name is synchronous. But you are making an ajax call to get the name and therefore the code is asynchronous.
var productName = myObj.getProductName(5);
You need to use dojo/Deferred to handle the asynchronous call.
function getProductName(productId) {
var d = new dojo.Deferred();
dojo.xhrPost({
url: '/shop/dataProduct.php',
handleAs: 'json',
content: {productId:productId},
load: function(response, ioArgs) {
if (!response.error) {
var productName = ???;
d.resolve(productName);
} else {
d.reject(response.error);
}
},
error: function(err) {
d.reject(err);
}
});
return d;
}
Usage:
getProductName(1).then(
function(productName) {
// do something with product name
}, function(error) {
// handle error
});
http://dojotoolkit.org/reference-guide/1.8/dojo/Deferred.html

Categories

Resources