Note that there are some explanatory texts on larger screens.

plurals
  1. POjQuery.when understanding
    primarykey
    data
    text
    <p>I am trying to use the <code>jQuery.when</code> to fire two <code>ajax</code> requests and then call some function after the two requests have completed. Here's my code:</p> <pre><code>var count = 0; var dfr; var showData = function(data) { dfr.resolve(); alert(count); // Do something with my data data received }; var method1 = function() { dfr = $.Deferred(); return $.ajax('localhost/MyDataService/DataMethod_ReturnsData', { dataType: "jsonp", jsonp: "$callback", success: showData }); }; var method2 = function() { return $.ajax('localhost/MyDataService/DataMethod_ReturnsCount', { dataType: "jsonp", jsonp: "$callback", success: function(data) { count = data.d.__count; } }); }; $.when(method1(), method2()) .then(showData()); </code></pre> <p>However this is not working as expected. Ajax call in <code>method1</code> will return data which is to be used in <code>showData()</code> and Ajax call in <code>method2</code> will return count which is to be assigned to var count and later used in <code>showData()</code>. </p> <p>But when I fire the above code, <code>method1</code> gets called and then <code>method2</code> and then <code>showData</code> leaving the data in <code>showData</code> as <code>'undefined'</code>. How can I achieve this via <code>$.when</code> which as far as I know proceeds only when both functions returning <code>$.promise</code> are executed. I want that both the ajax calls should be called in parallel and later results be displayed based on results from both calls.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload