-2

I am currently creating an AJAX call which queries a controller and returns the appropriate reponse. The only issue is is that the response is coming back as undefined doe to the async nature of the AJAX cal. I am unsure as to how I tell the function to wait for the response. Here is my code:

View:

jQuery(document).on("click", "#payment .membership", function(e) {
        e.preventDefault(); 
        var price = SignUpObject.membershipClick(jQuery(this).attr("data-membership-id"));
        alert(price);
    });

Javascript Library Function (which is within an object):

var SignUpObject = {
    membershipClick : function(membershipDetailsId) {           
        jQuery.ajax({
            type      :  'POST',
            dataType  :  'json',            
            url       :  'api/membership-choice',
            data      :  'membershipid=' + membershipDetailsId
        }).done(function(response) {
            return response
        });
    }
}

The PHP that the AJAX call is calling returns the correct response back so I don't need to include them here. Can anyone tell me how to make the AJAX call wait for a response? Thanks

James
  • 2,800
  • 7
  • 45
  • 81
  • possible duplicate of [How to return the response from an Ajax call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Benjamin Gruenbaum Nov 03 '14 at 15:24

2 Answers2

0

You've got two problems:

1) You're attempting to call the response synchronously, before the (asynchronous) request has completed.

2) membershipClick does not return the request object, so you've got no means of hooking a completion callback onto it.

To fix:

1) Change the line

jQuery.ajax({...

to

return jQuery.ajax({

2) Change the line

alert(price);

to

price.done(function(response) { alert(response); });

However, the variable price would be better named something like price_request, since it stores a reference to the request, not the actual price (which is the response.)

Mitya
  • 33,629
  • 9
  • 60
  • 107
0

Change

}).done(function(response) {
return response

});

For:

}), success: function(response) {
return response

};

pmereles
  • 401
  • 7
  • 10