AJAX response into an object [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 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);
});

Related

How to get Variable to equal results from function with AJAX [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I'm trying to set a variable from a ajax call that runs a function. The code below returns imgurlthumbvar in the console log put the alert(test) says it's undefined. I did some research and found out that the it has something to do with AJAX being asynchronous. Could anyone please help. Thanks in advance!
function displayimg(id2){
$.ajax({
url:'getphotos.php',
type:'POST',
dataType: "JSON",
data:{id2:id2},
success: function(result){
$.each(result, function(){
imgurlvar = this.imgurl;
imgurlthumbvar = this.imgurlthumb;
console.log(imgurlthumbvar)
//console.log('test')
return imgurlthumbvar
})
}
});
}
$('#test123').click(function(){
var test = displayimg(7)
alert(test)
})
Try
function displayimg(id2) {
return $.ajax({
url: 'getphotos.php',
type: 'POST',
dataType: "JSON",
data: {
id2: id2
}
});
}
// AJAX returns a promise
$('#test123').click(async function(){
var result = await displayimg(7); // result is AJAX response
var test;
$.each(result, function(){
imgurlvar = this.imgurl;
imgurlthumbvar = this.imgurlthumb;
console.log(imgurlthumbvar)
//console.log('test')
test = imgurlthumbvar
})
alert(test)
});
await makes an asynchronus call look and behave like synchronous but without actually making it synchronous (sync. calls are discouraged due to UI freezing issue

JS Function including AJAX returning undefined [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
function idToUnitNum(id){
$.ajax({
type: "POST",
url: "ajax_officerFromId.php",
data: {'id': id},
success: function(dataString) {
ofd = JSON.parse(dataString);
var result = ofd.data;
console.log(result);
return result;
}
});
}
This is the function. It's called from another function. I tried testing it's output by logging result before it returns, and it displays the appropriate result.
Result (JSON):
{"success":"true","time":1524462577,"data":"ADMIN"}
However, when I try catching the variable (a string), it does shows as "undefined".
It's probably a stupid mistake.
Calling the function:
var unitnum = idToUnitNum(adata.arresting_officer);
console.log(unitnum);
Thank you for your assistance!
pass callback function to idToUnitNum. something like below
function idToUnitNum(id,callback){
$.ajax({
type: "POST",
url: "ajax_officerFromId.php",
data: {'id': id},
success: function(dataString) {
ofd = JSON.parse(dataString);
var result = ofd.data;
console.log(result);
callback(result);
}
});
}
Hi Please change the AJAX function like this :
function idToUnitNum(id){
var dfd = $.Deferred();
$.ajax({
type: "POST",
url: "ajax_officerFromId.php",
data: {'id': id},
success: function(dataString) {
ofd = JSON.parse(dataString);
var result = ofd.data;
dfd.resolve(result);
// return result;
}
});
return dfd.promise();
}
And you can use this function like this
idToUnitNum(adata.arresting_officer).done(function(response){
console.log(response);
});
FYI : not tested code
function idToUnitNum(id){
var result = '';
$.ajax({
type: "POST",
url: "ajax_officerFromId.php",
async: false,
data: {'id': id},
success: function(dataString) {
ofd = JSON.parse(dataString);
result = ofd.data;
}
});
return result;
}
Thank you to whoever suggested I turn off async and call it outside fo the AJAX request. Solved the issue.
You should either use a callback function as a parameter or, even better, use promises. Simply put return in front of your ajax call and call .then() on the return value to read the result when it is available.
This has been asked many times, so you shouldn’t have any trouble finding more information about these solutions

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.
});

Ajax global variables or synchronous AJAX [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I want to get data from another page using AJAX. I also want to wrap this AJAX call into my "user defined function".
But I can not write like this:
function func(){
var tmp;
$.ajax({
url: 'url',
type: "POST",
dataType: "json",
success: function (data) {
tmp=data;
}
});
return tmp;
}
because AJAX is asynchronous and this code returns - "undefined".
When AJAX async param set to false
var tmp=$.ajax({...});
possible do the trick.
I also can create some global variables and write like this:
function setMyVariable(){
$.ajax({
...
success: function (data) {
myGlobalVariable=data;
}
});
}
The question is - Is it good practice to use global variables in this case?
Or it is completely wrong and I need search something else
The best practice would be to return the promise from $.ajax:
function func(){
var tmp;
return $.ajax({
url: 'url',
type: "POST",
dataType: "json",
});
}
Then you can do function().done(function(result) { ... } );

javascript variable is not showing correct value [duplicate]

This question already has answers here:
How to add callback to AJAX variable assignment
(4 answers)
Closed 8 years ago.
i have this ajax call function.
function saveData(ip)
{
$JQ.ajax({
type: "POST",
url: "all_actions.php",
data:
{
page_url:document.URL,
ip_address:ip
},
success: function(responce)
{
if(responce)
{
var newtoken;
newtoken=responce;
return newtoken;
}
}
});
}
Then i have another function
function getToken()
{
var ip=myip
var mytoken;
mytoken=saveData(ip);
alert(mytoken);
}
My token giving undefined in alert.Although if i alert newtoken variable in savedata response it gives correct value in alert box.why if i return that avlue it does not assigned to mytoken.
is it something time delay issue.??
Need your help...
You cannot return from an asynchronous call.
You have to consume the return data inside the success function. Whatever you are going to do with token, write that code inside the success handler.
success: function(responce)
{
if(responce)
{
var newtoken;
newtoken=responce;
// Global variable
sourceid = newtoken;
return newtoken; // This won't work
}
}
Also
function getToken()
{
var ip=myip
var mytoken;
mytoken=saveData(ip); // This won't return any data
alert(mytoken); // This won't give you anything useful
}
Hi friends This is solution that for i was looking.
function saveData(ip)
{
return $JQ.ajax({
type: "POST",
url: "all_actions.php",
data:
{
page_url:document.URL,
ip_address:ip
},
async: false,
}).responseText;
}
function getToken()
{
var ip=myip
var mytoken;
mytoken=saveData(ip);
return mytoken;
}
The first 'A' in AJAX is 'Asynchronous'. Your alert is running before the AJAX request has had a chance to complete. You need to handle whatever you wish to do with the response inside of the success: function() or .done() functions of jQuery:
success: function(responce)
{
if(responce)
{
var newtoken = responce;
// Work here with newtoken...
}
}

Categories

Resources