Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery. Assign JSON as a result to a variable

I use this helper function to receive JSON results for my requests:

function getData(url) {
    $.get(url,
         function(data) {
             response = data;
             return response;
         }, 'application/json');
}

I give it some string as a part of url from my web application, like '/api/getusers', so it looks like getData('/api/getusers'). Now I need that string result containing JSON data that I receive from the url to be assigned to my variable, so it would look like this: var result = getData('/api/getusers'). Then I will process this JSON data. The problem is with the returning the response variable. It's undefined. Thanks!

like image 679
Sergei Basharov Avatar asked Jan 27 '26 02:01

Sergei Basharov


2 Answers

try this

function getData(url) {
var data;
    $.ajax({
        async: false, //thats the trick
        url: 'http://www.example.com',
        dataType: 'json',
        success: function(response){
           data = response;
        }
    });
    return data;
}
like image 192
Valerij Avatar answered Jan 28 '26 15:01

Valerij


It's an asynchronous operation, meaning that function(data) { ... } runs later when the response from the server is available, long after you returned from getData(). Instead, kick off whatever you need from that function, for example:

function getData(url, callback) {
    $.get(url, callback, 'application/json');
}

Then when you're calling it, pass in a function or reference to a function that uses the response, like this:

getData("myPage.php", function(data) {
  alert("The data returned was: " + data);
});
like image 43
Nick Craver Avatar answered Jan 28 '26 15:01

Nick Craver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!