Ajax Jquery: how return result? [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
In script-a.js I have this function:
function callGetAjax(url,callback) {
$.get(url, {}, function(result) {
// this will call the callback and pass the result
callback(result);
});
}
In script-b.js I call it:
var url = '/feed/location';
callGetAjax(url,function(result)
{
//console.log(result); <= of course this logs right
data = result;
return data;
});
console.log(result); // <= ReferenceError: result is not defined
console.log(data); // <= ReferenceError: data is not defined
I don't want make async:false but I need to "export" data to elaborate it. Thank you.

Ajax is an async tool so you can use data only inside it. So, if you need to alter the dom with data you should do it directly:
var url = '/feed/location';
callGetAjax(url,function(result)
{
//console.log(result); <= of course this logs right
data = result;
$('#some_dome_item').html(data);
});

Related

What's the best way to have a JS function do a simple AJAX true/false request and return that result [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
What's the best way to have a JS function to do a simple AJAX true/false request and return that result.
I want to do a simple AJAX request, in a JS function, that checks if a users session is still active. The function should wait for the AJAX request to complete and return true or false.
I've achieved this using a setInterval but I don't think this is the best way. I tried to use jQuery $.when but I couldn't get the function to return a result.
function checkSessionIsStillActive(){
var result; //ajax result will be put in here. It will be undefined until ajax complete
$.getJSON('application/app_cfc/session_check.cfm/ajax')
.done(function( data ) {
// return the value
result = data.session_active;
});
// Do an interval loop check until the result is defined
var interval_check = setInterval(function(){
// Return the result as soon as we have it
if(result != undefined ){
// Clear this interval loop
clearInterval(interval_check);
// return the result to the calling function
return result;
}
}, 100);
}
You should read about async javascript, especially Promise.
function checkSessionIsStillActive(){
return new Promise((resolve, reject) => {
$.getJSON('application/app_cfc/session_check.cfm/ajax')
.done(data => {
// return the value
result = data.session_active;
resolve(result);
});
});
}
If you call the function you would then do
checkSessionIsStillActive().then(data => {
// result from function is available here
});
Use fetch() API and ASYNC code.
async function isSessionActive(url) {
let data = await fetch(url);
let jsonData = await data.json();
jsonData.sessionActive ? true : false;
}
let result = isSessionActive('application/app_cfc/session_check.cfm/ajax');
console.log(result) // either true or false

Get result from JavaScript Promise (.then function) when doing API call? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I'm a total beginner at Javascript, and I'm trying to get some data from an API, and have code that looks roughly like this:
function getData(uid) {
app.login({ email: userEmail, password: userPassword}).then(function(response){
var user = response.user;
var result = user.read(uid).then(function(){
return "foobar";
});
return result;
});
}
function doStuff(uid) {
var result = getData(uid);
// do stuff on result
console.log(result); //returns promise
}
So I want to access the result var result = getData(user, uid); which only returns a Promise object. What's the best way to get access to the "foobar" result?
You can't return a result from a deferred request. What you should do is use a callback function like this...
function getData(uid, callback) {
app.login({ email: userEmail, password: userPassword}).then(function(response){
var user = response.user;
var result = user.read(uid).then(function(){
return "foobar";
});
callback(result);
});
}
function doStuff(uid) {
getData(uid, function(result) {
// do stuff on result
console.log(result); //returns promise
});
}

How to save the response from an asynchronous call to variable [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 API call and I expected to write response to friends variable.
getFriends = function() {
return VK.Api.call('friends.get', {}, function(response) {
if (response.response)
response.response;
});
};
var friends = getFriends();
console.log(friends) // undefined;
In my previous question one guy told me that I can fix it with callback function and close my question. I implement a callback but again I can't get a response.
var getFriends = function(callbackFn) {
return VK.Api.call('friends.get', {}, function(response) {
if (response.response) {
callbackFn(response.response);
}
});
};
var friends = getFriends(function(list) { return list; });
How I can write response.response to variable for a lot of next manipulations?
It's actually much simpler
var friends = null;
VK.Api.call('friends.get', {}, function(response) {
if (response.response) {
friends = response.response;
console.log(friends);
}
}

variable not being returned (unidentified) - AngularJS [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
In my controller I am calling the function
function initialiseQuizContent(quizIdArray){
alert(getQuizService.getQuizContent(quizIdArray));
}
which calls the a method in the following service
app.service('getQuizService', function($http) {
var quizArray;
this.setQuizArray = function(quiz){
quizArray = quiz;
};
this.getQuizArray = function(){
return quizArray;
};
this.getQuizContent = function(quizArray){
var $promise=$http.get("http://localhost/PHP/getQuizContent.php", {'quizArray': quizArray}); //send data to addQuiz.php
var theReturn;
$promise.then(function(msg){
//alert(msg.data);
theReturn = msg.data;
});
return theReturn;
};
});
However the result I get for the alert is 'undefined'. I know that the call to the PHP file works fine as if I put 'alert(msg.data)' within the promise, as commented out above, then the correct array is returned. I am new to this so excuse any silly questions but it seems as if the value that is being returned for the 'getQuizContent()' method is done before the PHP file is executed and the msg.data is received? Resulting in the undefined variable 'theResult'.
I would appreciate any help. Thanks
Working with $http service means working with AJAX, the response is asynchronous, that why you got undefined, I would suggest changing your service and doing something like this:
app.service('getQuizService', function($http) {
var quizArray;
this.setQuizArray = function(quiz){
quizArray = quiz;
};
this.getQuizArray = function(){
return quizArray;
};
this.getQuizContent = function(quizArray){
var promise=$http.post("http://localhost/PHP/getQuizContent.php",
{'quizArray': quizArray}).then(function (response) {
console.log(response);
return response.data;
});
return promise;
};});
then in controller do something like this:
function initialiseQuizContent(quizIdArray){
getQuizService.getQuizContent(quizIdArray).then(function(data){
alert(data);
});
}

undefined variable after ajax request [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 using jQuery. I have a function that fetches data from a remote server called "get_cats". I call it to fill an array with the values returned. When AJAX is completed I want to return the values.
But It doesn't work, the value returned is undefined. This is pretty basic but I can't see where It fails. Does anyone has a clue ?
$(function () {
var url = "http://someurl.com/service/";
var cats = [];
cats = get_cats(url);
function get_cats(url) {
var categories = [];
$.getJSON(url + "cats", function (data) {
$.each(data, function (i) {
categories.push(data[i].name);
});
return categories;
});
}
$(document).ajaxStop(function () {
console.log(cats); // fails and returns undefined :'(
});
});
Oh no AJAX is asynchronous, you cannot return anything from it. You should consume the results of an AJAX request only inside the success callback:
$(function () {
var url = "http://someurl.com/service/";
get_cats(url);
function get_cats(url) {
var categories = [];
$.getJSON(url + "cats", function (data) {
$.each(data, function (i) {
categories.push(data[i].name);
});
// Only here you can consume the results of the AJAX request
// Do not attempt to return them, it doesn't make any sense
console.log(categories);
});
}
});
You can try:
$.ajaxSetup({async:false});
before AJAX call.
But it will stop browser while respone will be returned.

Categories

Resources