2

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!

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
Sergei Basharov
  • 51,276
  • 73
  • 200
  • 335

3 Answers3

8

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;
}
Valerij
  • 27,090
  • 1
  • 26
  • 42
6

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);
});
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
1

Use $.ajax

$.ajax({
    url: 'http://www.example.com',
    dataType: 'json',
    success: function(data){
       alert(data.Id);
    }
});
Zhasulan Berdibekov
  • 1,077
  • 3
  • 19
  • 39