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.
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.
you can pass in a callback function:
function checkUserIdExists(userid, callback) { $.ajax({ ... success: callback }); } checkUserIdExists(4, function(data) { });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With