views:

31

answers:

3

I am calling a function that returns the result of an ajax GET request using jQuery.

How do you return its result through the function to the callee?

function makePrPoContent(s_firstName, s_lastName, s_email){

   $.get('/includes/snippets/privacy_policy.jsp', {
      firstName: s_firstName,
      lastName: s_lastName,
      email: s_email
   }, function(data){
      return data;
   });
}

var mainContent = makePrPoContent('Stack', 'Overflow', '[email protected]');
console.log(mainContent);

The above doesn't return anything, probably since the return is within the ajax callback, so therefore the return doesn't return to makePrPoContent.

Also tried this:

function makePrPoContent(s_firstName, s_lastName, s_email){
   var returnData = false;
   $.get('/includes/snippets/privacy_policy.jsp', {
      firstName: s_firstName,
      lastName: s_lastName,
      email: s_email
   }, function(data){
      returnData = data;
   });
   return returnData;
}

That doesn't work because it returns before the ajax call is finished, therefore returnData is still false.

I can verify that there is indeed data returned through the ajax callback. When I log the data in the callback it has what I need.

How would I get this to return to my function?

Thanks for the help in advance!

A: 

Your better off passing the result to another function to be processed. Basically you cannot do what you're proposing as the AJAX is asynchronous and therefore won't wait to get the result.

So just call someotherFunction(data) from inside your callback.

laurencek
+3  A: 

AJAX is asynchronous, so you can best approach it that way, you can change the function like this:

function makePrPoContent(s_firstName, s_lastName, s_email, callback){
   $.get('/includes/snippets/privacy_policy.jsp', {
      firstName: s_firstName,
      lastName: s_lastName,
      email: s_email
   }, callback);
}

Then when you call it, you pass in the function that takes the result, like this:

makePrPoContent('Stack', 'Overflow', '[email protected]', function(data) {
  console.log(data);
});
Nick Craver
+1  A: 

if you realy want to do this (wich usualy is a bad idea, but your choice - you should realy use the callbacks if you work with ajax) you have to set the ajax-request to be synchonously instead of asynchonous (thats the A in ajax and the important and innovative idea behind all that).

how to set it to behave synchonous should be easy to find in the jquery documentation

oezi