Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return Value from inside of $.ajax() function

Tags:

jquery

ajax

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;
}
like image 977
BillPull Avatar asked Nov 18 '11 18:11

BillPull


1 Answers

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.

like image 181
RoccoC5 Avatar answered Oct 13 '22 11:10

RoccoC5