Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript function that returns AJAX call data [duplicate]

I would like to create a JavaScript function which returns the value of a jQuery AJAX call. I would like something like this.

function checkUserIdExists(userid){     return $.ajax({         url: 'theurl',         type: 'GET',         cache: false,         data: {            userid: userid         },         success: function(data){             return data;         }     }); } 

I know I can do this by setting async to false but I would rather not.

like image 480
Timothy Ruhle Avatar asked Mar 01 '11 04:03

Timothy Ruhle


2 Answers

You can't return data returned by an AJAX call unless you want to call it synchronously (and you don't – trust me). But what you can return is a promise of a data returned by an AJAX call and you can do it actually in a very elegant way.

(UPDATE: Please note that currently jQuery Promises are not compatible with the Promises/A+ specification - more info in this answer.)

Basically you can return the return value of your $.ajax(...) call:

function checkUserIdExists(userid){     return $.ajax({         url: 'theurl',         type: 'GET',         cache: false,         data: {            userid: userid         }     }); } 

and someone who calls your function can use it like this:

checkUserIdExists(userid).success(function (data) {     // do something with data }); 

See this post of mine for a better explanation and demos if you are interested.

like image 77
rsp Avatar answered Oct 03 '22 00:10

rsp


you can pass in a callback function:

function checkUserIdExists(userid, callback) {     $.ajax({         ...         success: callback     }); }  checkUserIdExists(4, function(data) {  }); 
like image 45
Omer Bokhari Avatar answered Oct 03 '22 01:10

Omer Bokhari