0

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);
Simon Adcock
  • 3,554
  • 3
  • 25
  • 41
Brandon
  • 311
  • 2
  • 16
  • you can't do that. Even after fixing the dozen or so syntax errors, you can't return the response from an ajax request. – Kevin B Mar 21 '14 at 20:37

3 Answers3

0

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);
    });
}
Mike Thomsen
  • 36,828
  • 10
  • 60
  • 83
0

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;
   });
}),
Ennosigaeon
  • 442
  • 7
  • 15
0

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);
});
hugomg
  • 68,213
  • 24
  • 160
  • 246