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

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

Related

JQuery.when() isn't waiting for a function return [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I have the following code structure :
var firstPagePromise = $.ajax('url1').then(function (data) {
//do stuff
});
var secondPagePromise = $.ajax('url2').then(function (data) {
//do stuff
});
$.when(firstPagePromise, secondPagePromise).done(function () {
// do stuff
});
I want to execute some code after doing two request using JQuery.when()
. Written like this, it's working, but I would like to put the two requests in functions for easier maintenance of the code and I'm unsure how to do that.
function fetchFirstPage() {
var firstPagePromise = $.ajax('url1').then(function (data) {
//do stuff
});
return firstPagePromise;
}
var firstPagePromise = fetchFirstPage();
// same for the second page ...
$.when(firstPagePromise, secondPagePromise).done(function () {
// do stuff
});
this does not work and seems to fire when() without waiting for the execution of the two functions, is there any way I could execute the code in the when function only if the two previous function have ended ?
The following code shows my issue on a minimal example, I'd like to get the variable title to print in the console after the call to when but I get "undefined" instead. I think that I understand what's going on, inside the function fetchPage(), title is returned before the request finishes. I think that a callback function could resolve the issue, however, is there any other way ?
function fetchPage() { //fetch the random start page
var title;
var pagePromise = $.ajax('https://en.wikipedia.org/w/api.php?action=query&origin=*&format=json&list=random&continue=-||&rnnamespace=0&rnlimit=1').then(function (data) {
title = data.query.random[0].title;
console.log("in request : " + title);
});
console.log("in function return : " + title);
return [title,pagePromise];
}
var firstPageResult = fetchPage();
var title = firstPageResult[0];
var pagePromise = firstPageResult[1];
$.when(pagePromise).done(function() {
console.log("in when : " + title);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>

Angular JS Factory $http returns nothing [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I am a beginner and working on existing code, making few changes to post payload.
I am making a get call inside a factory like this,
var providerUrl = "/" + OPENMRS_CONTEXT_PATH + "/ws/rest/v1/session";
\$http.get(providerUrl).then(function(response){
var uuid =response.data.user.uuid;
console.log(uuid); //1st console.log
}, function(error){
console.log(error);
});
console.log(uuid); //2nd console.log
Now the 2nd log doesn't actually shows anything probably because of the asynchronous nature.
I need to use this UUID value in the factory itself.
Because I am posting a payload using $http post call
like this from the same factory,
var json = {
patient: patient,
uuid: .... //HERE GOES THE GET RESPONSE
encounterType: window.constantConfigObj.encounterTypeVisitNote,
visit: visitId,
encounterDatetime: date2
};
If someone can explain me how this can be done, it would be really helpful.
Thanks
function getdata(){
var providerUrl = "/" + OPENMRS_CONTEXT_PATH + "/ws/rest/v1/session";
return $http.get(providerUrl).then(function(response){
return response.data.user.uuid;
}, function(error){
console.log(error);
});
}
var json = {
patient: patient,
uuid: getdata,
encounterType: window.constantConfigObj.encounterTypeVisitNote,
visit: visitId,
encounterDatetime: date2
};
in controller
factory.uuid().then((resp) => {console.log(resp)})

Ajax Jquery: how return result? [duplicate]

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

Return a nested function from inside a node module [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 8 years ago.
I trigger a function using require() in my app.js file and the result returned is 'undefined'. I think this is due to the function being nested. What is the best way to return the nested value. I have tried the method below but the function appears to be asynchronous and the returned value is returned as undefined before the data is provided.
app sample code --
app.get("/twitter/:handle", function (req, res) {
var handle = req.params.handle;
var twitter = require('./module/twitter');
var data = twitter.searchHandle(handle);
console.log(data);
res.sendStatus(data);
});
module sample code -
var twitter = {
searchHandle: function(handle){
var dataToReturn;
T.get('search/tweets', { q: handle, count: 100 }, function(err, data, response) {
dataToReturn = data;
});
return(dataToReturn);
}
};
module.exports = twitter;
searchHandle is an async call. Returning dataToReturn will always be undefined as it's value has not yet been populated. You will need to pass a callback function to searchHandle to be executed once dataToReturn is populated.
//app.js
var handle = req.params.handle;
var twitter = require('./module/twitter');
var data = twitter.searchHandle(handle, function (data) {
console.log(data);
res.sendStatus(data);
});
//twitter.js
var twitter = {
searchHandle: function(handle, callback){
T.get('search/tweets', { q: handle, count: 100 }, function(err, data, response) {
callback(data);
});
}
};
module.exports = twitter;

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