jquery - creating a generic ajax function
<blockquote>
  <p><strong>Possible Duplicate:</strong><br>
  <a href="http://stackoverflow.com/questions/3203283/jquery-ajax-always-returns-undefined">jQuery Ajax always returns &ldquo;undefined&rdquo;?</a>  </p>
</blockquote>



<p>I'm trying to come up with a generic jquery ajax function which takes the url &amp; parameters and returns the result. I'm trying to avoid using <code>async:false</code> as it locks up the browser. If I use <code>success</code> 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 <code>complete</code>, the <code>persons</code> object is still null in the <code>LoadPersons</code> method as it doesn't wait for the data to be returned from the ajax call. If place an <code>alert(persons)</code> in the <code>complete</code> callback, I get <code>[object][Object]</code> 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.</p>

<p>Here's my code -</p>

<pre><code>  &lt;script type="text/javascript"&gt;
    $(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;
                }
            });
   &lt;/script&gt;
</code></pre>
