Undefined return in $.get jquery [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
How to return AJAX response Text? [duplicate]
(2 answers)
Closed 9 years ago.
This question is already answered and voted. My edits are related to making it clearer and share some new knowledge acquired for other developers, I'm not expecting new answers.
I'm reading an XML with jQuery, but when I try to show an alert it's fully working; however, when I try to return the value it always gives me a message that it's undefined.
function getText(value){
var val;
var lang;
var location;
lang=getLanguage();
if (lang=='en')
lang='';
else
lang+='.';
location="resources/AppResources."+lang+'xml';
$.get(location, function (xml) {
$(xml).find("data").each(function () {
var name=$(this).attr('name');
if (name===value)
return $(this).find('value').text();
});
});
}
This is the code that calls it:
$(document).ready(function() {
alert(getText('AppTitle'));
});
If I add an alert in the return statement it shows me the value selected.
Small update:
As Arun P Johny explained in his answer, the missed part in my code was the callback that are defined by Mozilla in this way:
A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.

You can't return a value from a async method, the easiest solution is to use a callback function like this one:
function getText(value, callback) {
var val;
var lang;
var location;
lang = getLanguage();
if (lang == 'en')
lang = '';
else
lang += '.';
location = "resources/AppResources." + lang + 'xml';
$.get(location, function (xml) {
$(xml).find('data[name="' + value + '"]').each(function () {
callback($(this).find('value').text());
});
});
}
$(document).ready(function() {
getText('AppTitle', function(value){
alert(value);
})
});

Related

Callback function for storing JSON to a variable [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I had a previous question where I was having issues for getting json from an url and storing it to a variable in order to pass it further to a function. I managed to get redirected to a solution that seemed promising, but it's still giving me undefined. The proposal was to use a callback as follows, but it doesn't seem to do the job.
var space = "";
function spaceCallback(data) {
fplan = data.space['space'];
}
function getSpace() {
var url = "http://localhost:8000/spaces/send_space/"
$.getJSON(url, function (data) {
spaceCallback(data);
});
}
I would need to pass space to blueprint3d.model.loadSerialized(space);.
What am I missing here?
Is it possible that you need to return your function?
function getSpace() {
var url = "http://localhost:8000/spaces/send_space/"
$.getJSON(url, function (data) {
return spaceCallback(data);
});
}
or ES6:
function getSpace() {
var url = "http://localhost:8000/spaces/send_space/"
$.getJSON(url, (data) => spaceCallback(data));
}

Why isn't my function returning my array? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
function getContent(type) {
var content = [];
$.get(`/${type}.json`, function(data) {
$.each(data, function(index, hash) {
content.push(hash);
});
// 1. content = [object, object, etc..]
});
// 2. content = []
return content;
}
I need help understanding this. Why is content empty on the 2nd comment? From the looks of it, the function starts pushing hash into a NEW variable called content, instead of referencing the content that I explicitly made in the beginning. How do I fix this? Why is javascript scope so confusing.
Also, to fix this, I global variables. WHY can my function have access to a global variable content anywhere in the function, but calling content in the beginning function, it won't have access to certain places.
Because $.get is async. The nature of this call is that it goes into the event loop and doesn't modify your current program flow.
You should use callback.
function getContent(type, callback) {
var content = [];
$.get(`/${type}.json`, function(data) {
$.each(data, function(index, hash) {
content.push(hash);
});
callback( content );
});
}
getContent("items", function( content ) {
console.log(content);
});
To give you a better example you can also use your flow, but it should look like this :
function getContent(type, callback) {
var content = [];
$.get(`/${type}.json`, function(data) {
$.each(data, function(index, hash) {
content.push(hash);
});
callback();
});
return content;
}
var items = getContent("items", function() {
console.log( items );
});

JavaScript recursive setTimeout [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 6 years ago.
I defined this class in JavaScript:
function Signal(lbl, ho, tag) {
this.lbl = lbl;
this.ho = ho;
this.tag = tag;
this.getstatus = function () {
if (this.ho) {
$.get('/get.cgi?' + this.tag + '=?0', function (data) {
console.log(data);
setTimeout(this.getstatus, 1000);
});
}
};
}
Once getstatus is called, it should start calling itself with setTimout, but it doesn't! It only works one time.
If I use a function without a class, it works!
Please help me out.
Thanks!
The problem is when getStatus is invoked by the timer, this inside the method does not refer to the object, you can pass a custom value for this using bind(). Also note that in the ajax callback this refers to the ajax settings object.
function Signal(lbl, ho, tag) {
this.lbl = lbl;
this.ho = ho;
this.tag = tag;
this.getstatus = function () {
if (this.ho) {
var signal = this;
$.get('/get.cgi?' + this.tag + '=?0', function (data) {
console.log(data);
setTimeout(signal.getstatus.bind(signal), 1000);
});
}
};
}

How can I alert the contents returned from this function? [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 function that returns JSON information. I want to be able to store that into a variable and then use alert and the variable name to display the content returned from that function. Here is my code:
var getStuff2 (function (num) {
$.getJSON('http://whateverorigin.org/get?url=' + encodeURIComponent('http://catholic.com/api-radio/' + num) + '&callback=?', function(data) {
//console.log(data.contents);
//$('#response').text(data.contents);
obj = data.contents;
//alert(obj);
}];
return data.contents;
});
});
function getData(){
getStuff2(6387);
}
getData();
alert(getStuff2);
You have to put the alert inside of the callback handler for the AJAX function. AJAX calls are asynchronous which means that if you do something like this, the return won't work in the order you expect:
function getData() {
doAjax(function(data) {
obj = data.contents;
});
alert(obj);
}
You see, the AJAX call will return when it returns, and all of the code after it will just keep executing while the AJAX call is still waiting on a response.
So what you have to do is this:
function getData() {
doAjax(function(data) {
obj = data.content;
alert(obj);
});
}
I assume, that data.contents is a object, so your alert output will look something like [object object], so you just can't alert the content.
To make it globally available just store the content in a gloabl variable.
var result;
var getStuff2 (function(num) {
$.getJson(url, function(data)
result = data.contents;
});
}),
asynchronous functions cannot return values. Instead you need to explicitly do something with the value from inside the AJAX callback.
function getStuff(num, onContents){
$.getJSON(..., function(data){
//call the oncontents callback instead of returning
onContents(data.contents);
});
}
//when calling getstuff, pass a function that tells what to do with the contents
getStuff(6387, function(contents){
console.log(contents);
});

JavaScript asynchronous return value / assignment with jQuery [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I have the following jQuery Function. I'm trying to return the GUID value shown here in the alert(); The alert works fine and the value is populated, however I can't seem to assign it to a variable and return its value.
Ultimately I need to access the GUID value in other functions, etc. Everything I've tried only displays as undefined.
I'd like to do something like this:
function trackPage(){
var elqTracker = new jQuery.elq(459);
elqTracker.pageTrack({
success: function() {
elqTracker.getGUID(function(guid) {
alert(guid);
var returnValue = guid;
});
}
});
return returnValue;
}
var someGuid = trackPage();
So, this question has been asked a million times over, and I'm sure that everyone (myself included) tried this once.
It is just the nature of an asynchronous call, you can't use their results as a return value. Thats why they have you passing in a function that gets the result of the call, they can't return it either! Also notice that the elqTracker.pageTrack() function call returns IMMEDIATELY, therefore your returnValue is simply undefined.
Most people (see dfsq's answer) solve this problem by introducing a callback function as a paramater. This method is tried, and true – however jQuery has $.Deferred. This allows you to make your own asynchronous logic return a promise which you can then attach any number of callbacks to:
function trackPage(){
var elqTracker = new jQuery.elq( 459 ),
dfd = $.Deferred();
elqTracker.pageTrack({
success: function() {
elqTracker.getGUID(function( guid ) {
dfd.resolve( guid );
});
}
});
return dfd.promise();
}
// example use:
trackPage().done(function( guid ) {
alert( "Got GUID:" + guid );
});
Notice now that your trackPage() returns an object that you can attach callbacks to? You don't have to attach them immediately either.
var pageHit = trackPage().done(function( guid ) {
alert( "Page Hit GUID:" +guid );
});
$("button").click(function() {
pageHit.done( function( guid ) {
alert( "Clicked on Page GUID:" + guid );
});
});
Also, the jQuery AJAX module always returns promises as well, so the interface for all your AJAX stuff should be very similar if you make your own logic return promises.
As a side note: I'd like to point out that your var returnValue was in the wrong "scope" anyway. It needed to be declared in the outer scope of the trackPage function. Even with this fix, the concept still doesn't work.
Since you have asynchronous call the way you are trying to write code is not going to work (because by the moment of return returnValue; in the trackCode return value is not yet defined). Instead you should pass callback into trackPage:
function trackPage(callback) {
var elqTracker = new jQuery.elq(459);
elqTracker.pageTrack({
success: function() {
elqTracker.getGUID(function(guid) {
alert(guid);
// Instead of this: var returnValue = guid;
// You should use your callback function
callback(guid);
});
}
});
return returnValue;
}
trackCode(function(guid) {
// perform some actions with guid
});

Categories

Resources