10

How do I return a value from inside of an $.ajax function?

This is my basic setup:

function something(){
 var id = 0;
 $.ajax({
        'url':'/some/url',
        'type':'GET',
        'data':{'some':'data'},
        'success':function(data){
                     id = data['id'];
         }
   });

  return id;
}
Jasper
  • 75,717
  • 14
  • 151
  • 146
BillPull
  • 6,853
  • 15
  • 60
  • 99
  • 1
    possible duplicate of [Extjs, return Ajax return value](http://stackoverflow.com/questions/6917796/extjs-return-ajax-return-value) – locrizak Nov 18 '11 at 18:28

3 Answers3

17

Use a callback function, it is the JavaScript way:

function something(callback){
 $.ajax({
        'url':'/some/url',
        'type':'GET',
        'data':{'some':'data'},
        'success': callback
   });
}

something(function (data) {
    data['id']; // use it here
})
Joe
  • 80,724
  • 18
  • 127
  • 145
7

In addition to using a callback function as others have pointed out, another option would be to change it to a synchronous request:

function something(){
 var id = 0;
 $.ajax({
        'url':'/some/url',
        'type':'GET',
        'async':false,
        'data':{'some':'data'},
        'success':function(data){
                     id = data['id'];
         }
   });

  return id;
}

Keep in mind that a synchronous call is a blocking call while the request is active.

RoccoC5
  • 4,185
  • 16
  • 20
  • Good answer if you are doing something like form field validation and you actually want to wait to hear back from the server before revealing additional fields, for example, though you'll probably want to include a timeout. – terraling Feb 03 '14 at 17:04
3

Since AJAX is asynchronous, you can't, because your AJAX call will not return immediately. What you can do instead, what people usually do, is take a callback function and then call that with the return value. For example:

function something(callback) {
     var id = 0;
     $.ajax({
            'url':'/some/url',
            'type':'GET',
            'data':{'some':'data'},
            'success':function(data){
                 callback(data['id']);
             }
       });
}

something(function(id) {
    alert(id);
});

Note that you could always make your request synchronous and it would wait until it has data and you could return it immediately, but if your request takes more than a short moment, the whole script execution, and potentially the page, will be halted until it returns.

Alex Turpin
  • 46,743
  • 23
  • 113
  • 145