Passing variable outside ajax function [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
Please help - I have the following code which returns the variable 'results' in an alert. I want to use this variable outside of the function, and cannot get a callback, or outside declaration to work successfully. I'm sure I'm being a muppet, so I apologise for this basic question.....
<script src='http://code.jquery.com/jquery-1.9.1.js'></script>
<script>
$(function () {
$.ajax({
type: 'POST',
dataType: 'jsonp',
url: 'https://creator.zoho.com/api/json/my-company-culture/view/PageFeed_Report?scope=creatorapi&authtoken=d670dc68ac0f6d7ca389e7b206a25045',
success: function (results) {
var raw_result=JSON.stringify(results);
alert(results);
}
});
});
</script>

The jQuery 1.5+ way of resolving this is by using deferred objects:
var res;
var ajax = $.ajax({
type: 'POST',
dataType: 'jsonp',
url: ...
}).done(function(results) {
// you may safely use results here
res = results;
...
});
// you cannot safely use 'res' here, only in code
// invoked via a 'done' callback on the `$.ajax` promise
console.log(res); // undefined
It would be incorrect to attempt to copy results into some other variable in the outer scope unless you have ensured that no other code tries to access that variable until the AJAX call has completed.

Well, why not:
<script src='http://code.jquery.com/jquery-1.9.1.js'></script>
<script>
function do_the_stuff(smth) {
console.log(smth);//or do whatever you want to do with this data
}
$(function () {
$.ajax({
type: 'POST',
dataType: 'jsonp',
url: 'https://creator.zoho.com/api/json/my-company-culture/view/PageFeed_Report?scope=creatorapi&authtoken=d670dc68ac0f6d7ca389e7b206a25045',
success: function (results) {
var raw_result=JSON.stringify(results);
do_the_stuff(results);
}
});
});
</script>
That works fine for me. I don't see any problem.

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

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 function that return a value from ajax [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
Can you help with my problem. I want to make a function that will return list of doctors in different spicialization.. this is my code the problem is this code the function doctorlist returns emtpy value. what is the wrong with my code.
can you help me to fixed my problem please.
$(document).ready(function () {
$("#loaders").append("<center><img src='images/ajax-loader.gif'></center>");
doctorSpecialty();
});
function doctorSpecialty(){
$.ajax({
url: "http://localhost:8080/m-help/apps/json_special.php",
dataType: 'json',
async: true,
success: function(data) {
$("#list").empty();
$.each(data.result, function(){
var specialty = doctorList(this['specialization']);
$("#list").append("<li><a href='doctor-special.html?special=" +this['specialization']+ "' style='padding-left:10px'>" +this['specialization']+ ""+specialty+"</a></li>");
$("#loaders").fadeOut("fast");
});
}
});
}
function doctorList(e){
var specials = e;
var retSpecial = "";
$.ajax({
url: "http://localhost:8080/m-help/apps/json_special-doctor.php?s="+specials,
dataType: 'json',
async: true,
success: function(data) {
$.each(data.result, function(){
retSpecial = this['docFname'];
});
}
});
return retSpecial;
}
Anyone can help me to fixed this code for please.
The second call can not be async = true, since the loop continues and uses the answer (which has not arrived yet).
You should make the second async:false
OR
Use promises in the second call which will fill in the specialization and you need to cancel the DOM manipulation in the first ajax call.

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

Categories

Resources