Get resultfrom AJAX call into javascript variable [duplicate] - javascript
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;
},
});
Related
Javascript global variables not updating properly [duplicate]
This question already has answers here: How do I return the response from an asynchronous call? (41 answers) Closed 5 years ago. I need lines to be a global array but when I use console.log to compare values inside the function and outside the function, the inside one works fine but the outside one remains empty. Am I missing something here? var lines = new Array(); $.ajax({ type: "GET", url: "posts_replied_to.txt", success: function(content) { console.log("success"); lines = content.split('\n'); console.log(lines); }, error: function() { console.log("error"); } }); console.log(lines);
The problem here is not regarding global variables. Its the asynchronicity problem.By the time the console.log() outside your ajax request is called, the ajax success callback is not called.Thats why you won't get the right value. async function doAjax() { return await $.ajax({ type: "GET", url: "posts_replied_to.txt" }); } let lines = await doAjax() lines = content.split('\n') console.log(lines) Try this code using Async to get the expected result.
Yes,AJAX is asynchronous function.So, in outside 'console.log(lines)' command run before AJAX. You can AJAX asyn:false What does "async: false" do in jQuery.ajax()?
Before your GET response come your second console.log code also execute due to ajax is not async. Change as below, var lines = new Array(); $.ajax({ type: "GET", url: "posts_replied_to.txt", async: false, success: function(content) { console.log("success"); lines = content.split('\n'); console.log(lines); }, error: function() { console.log("error"); } }); console.log(lines);
Try using promise object returned by ajax call. var lines = new Array(); var promise_obj = $.ajax({ type: "GET", url: "posts_replied_to.txt" }).promise(); promise_obj.done(function(response) { lines = response.split('\n'); console.log(lines); // Rest of your logic goes here where you want to use lines. });
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.
How to return data to variable after ajax call success [duplicate]
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 PHP file returning data in required array format to my FlotChart, it's working. Now I'm trying to get this result in my script using ajax, however I cannot see result on global variable, as described below: myJS.js var EcomDashboard = function() { return { init: function() { var dataEarnings = NULL; $.ajax({ url:"operation.php", dataType: "text", success:function(data) { alert(data); //show my array [ [1, 20],[2,30],[3,14] ] dataEarnings = data; } }); alert(dataEarnings); //showing "NULL" but I need [ [1, 20],[2,30],[3,14] ] ... What is the correct way to assign to my variable date Earnings the array [[1, 20], [2.30], [3.14]]?
Javascript is an async language, it means it won't wait the http request to finish to execute the next line. you will have to assign the variable inside the success block. the alert shows null is becauseit got executed before the $.ajax http request line finishes. may be you can do this using a callback: dataAccess.js var ecomDashboard = function() { init: function(callback) { var dataEarnings = NULL; $.ajax({ url:"operation.php", dataType: "text", success:function(data) { callback(data); } }); } } controller.js ecomDashboard.init(function(data){ // data contains the array result // do your stuff }) event better: since jquery 1.5 there is incorporated promise interface, and .success is going to be deprecated. edited: thanks to Kevin B so with promise: dataAccess.js var ecomDashboard = function() { init: function(callback) { var dataEarnings = NULL; return $.ajax({ url:"operation.php", dataType: "text" }); } } controller.js ecomDashboard.init().done(function(data){ //do your stuff alert(data); }).fail(function(error){ //do stuff when error });
$.ajax({ url:"operation.php", dataType: "text", success:function(data) { doSomthingOnComplete(data); } }); function doSomthingOnComplete(data) { // do here your work }
This is occurring because that alert(dataEarnings) is executing before your ajax request resolves. The first letter in the AJAX acronym is Asynchronous. So, ultimately your data is being set properly you are just trying to access it before the asynchronous call completes.
JS Array values become 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 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]; }
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); });