Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery - creating a generic ajax function [duplicate]

Tags:

jquery

Possible Duplicate:
jQuery Ajax always returns “undefined”?

I'm trying to come up with a generic jquery ajax function which takes the url & parameters and returns the result. I'm trying to avoid using async:false as it locks up the browser. If I use success callback in the ajax call, the data returned is null due to the timing issue (success doesn't wait until the data is returned). If I use complete, the persons object is still null in the LoadPersons method as it doesn't wait for the data to be returned from the ajax call. If place an alert(persons) in the complete callback, I get [object][Object] so I'm getting the data back. How do I "fix" this issue? Am I talking sense? I would also ideally like to show a "loading.." image while it's doing this.

Here's my code -

  <script type="text/javascript">
    $(function() {
                var persons;
                var urlGetPersons = "Default.aspx/GetPersons";

                LoadPersons();

                function LoadPersons() {
                    persons = CallMethod(urlGetPersons, { });
                    if (persons != null) {
                        // do something with persons.
                    }
                }

                function CallMethod(url, parameters) {
                    var data;
                    $.ajax({
                        type: 'POST',
                        url: url,
                        data: JSON.stringify(parameters),
                        contentType: 'application/json;',
                        dataType: 'json',
                        success: function(result) {
                            data = result.d;
                        }, // use success?
                        complete: function(result) {
                            data = result.d;
                        } // or use complete?
                    });
                    return data;
                }
            });
   </script>
like image 529
tempid Avatar asked Dec 02 '22 00:12

tempid


1 Answers

This is what's comes to my mind with "generic" - but it's still asynchronous:

function CallMethod(url, parameters, successCallback) {
                //show loading... image

                $.ajax({
                    type: 'POST',
                    url: url,
                    data: JSON.stringify(parameters),
                    contentType: 'application/json;',
                    dataType: 'json',
                    success: successCallback,
                    error: function(xhr, textStatus, errorThrown) {
                        console.log('error');
                    }
                });
            }

CallMethod(url, pars, onSuccess);

function onSuccess(param) {
    //remove loading... image
    //do something with the response
}
like image 120
User Avatar answered Dec 09 '22 19:12

User