0

I have an arrey of items to insert in my cart, and I call N times a WebMethod with Ajax. When I finish to insert them, I need redirect to summary page.

function SellAll(){
 $.each(x,function (index, value) {

           $.ajax({
               type: "POST",
               url: "find.aspx/AddItem",
               data: "{'id': '" + value + "'}",
               contentType: "application/json; charset=utf-8",
               dataType: "json",
               async: "false",
               success: function (response) {
                  ...
               }
           });
    }) 
document.location.href = "summary.aspx";
};

If I call the function SellAll, the summery page is empty, but if I remove the redirect and I execute the function and I go (manually) in the summary page, I find my cart with items.

How can I fix this error?

Thanks!

Divyang Desai
  • 7,483
  • 13
  • 50
  • 76
LCR
  • 1
  • 1
  • Take a look to this answer http://stackoverflow.com/questions/3709597/wait-until-all-jquery-ajax-requests-are-done – Trouner Aug 26 '16 at 11:28
  • thx man :)this is nice http://stackoverflow.com/questions/3709597/wait-until-all-jquery-ajax-requests-are-done – LCR Aug 26 '16 at 16:45

1 Answers1

-1

Move document.location.href = "summary.aspx"; from its current location and it could be something like:

   $.when(SellAll()).done(function(a1, a2, a3, a4){
// the code here will be executed when all four ajax requests resolve.
// a1, a2, a3 and a4 are lists of length 3 containing the response text,
// status, and jqXHR object for each of the four ajax calls respectively.
 document.location.href = "summary.aspx";
});

Have no idea how this works since you are calling SellAll() itself several times (I have a feeling jQuery may want to fire the .when each time it completes.

If that is your issue then, what you could do is set some logic to create vars for each request and pass those to your $.when() function.

For ex:

var d1 = $.Deferred();
var d2 = $.Deferred();
var d3 = $.Deferred();

$.when( d1, d2, d3 ).done(function ( v1, v2, v3 ) {
    console.log( v1 ); // v1 is undefined
    console.log( v2 ); // v2 is "abc"
    console.log( v3 ); // v3 is an array [ 1, 2, 3, 4, 5 ]
 });

 d1.resolve();
 d2.resolve( "abc" );
 d3.resolve( 1, 2, 3, 4, 5 );`

Where d1 d2 and d3 would be the ajax requests you are queuing up.

  • 1
    i solved with this:http://stackoverflow.com/questions/3709597/wait-until-all-jquery-ajax-requests-are-done – LCR Aug 26 '16 at 16:44
  • Lol, I saw that answer and I thought this one might be better for you. I was afraid the other question would re-fire every time the ajax request finished. – Fernando Rodriguez Aug 26 '16 at 17:01