Sergei Basharov
Sergei Basharov

Reputation: 53850

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!

Upvotes: 2

Views: 14402

Answers (3)

Valerij
Valerij

Reputation: 27748

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

Upvotes: 8

Zhasulan Berdibekov
Zhasulan Berdibekov

Reputation: 1087

Use $.ajax

$.ajax({
    url: 'http://www.example.com',
    dataType: 'json',
    success: function(data){
       alert(data.Id);
    }
});

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630429

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

Upvotes: 6

Related Questions