Joh
Joh

Reputation: 166

Parts of ajax function can just be reached by debugging

I have an asp.net application in which I user jquery. In my jquery code I have a simple ajax request like this:

var allowDelete = true;
$.ajax({
              url: '...',
              dataType: 'json',
              type: 'post',
              data: { something...}
          })
          .success(function (response) {
              if (response.Passed) {
                 //do something
              }
              else {
                  //do something
                  allowDelete = false;
              }
          })
          .error(function () {
              // do something
          });

 if (allowDelete) {
//something
}

as you can see I want a var set false when my Passed var has the value false. When I just run the code without any breakpoints the allowDelete var is never set false. And when I put a breakpoint(in firebug) next to the row where I set the allowDelete false it never hits the breakpoint. But when I put a breakpoint at the beginnig of the function and debug through the whole ajax it everything works perfectly fine and get the result I wanted. Any idea where the mistake could be?

Upvotes: 0

Views: 84

Answers (1)

Igorovics
Igorovics

Reputation: 416

since you asked this question more than 1 month ago, it might be late, but hope that helps:

The reason is that AJAX is asynchronous: 1. You set allowDelete to true. 2. You call your AJAX function. It starts working, turns to your server, etc. 3. You check allowDelete. It is still true. 4. AJAX call returns, sets allowDelete to false if the conditions were OK (response is not Passed).

So because of asynchrony, allowDelete is being checked right after you call your AJAX function, doesn't wait for the answer(the AJAX callback method). Basically, your AJAX functions callback method runs too late.

When you use breakpoint, your AJAX call has enough time to get its answer from the server so the fourth point from above happens earlier than the third.

Upvotes: 1

Related Questions