0

Let's say I have this variable named nom that has a value of lol.

var nom = "lol";

Then I have this ajax function, if the data is false, I want to override the value of nom to whay, assuming the data is false.

$.ajax({ type: "POST", url: "micro/wave.php",
    data: { username: "some string" },
    success: function(data) {
        if (data == false) {
            nom = "whay";
        }
    }
});

Then if I alert the variable nom, it still alerts lol, it should alert whay because the data is false.

alert(nom);

Any solution for this stuff?

Wesley Brian Lachenal
  • 4,381
  • 9
  • 48
  • 81

3 Answers3

0

If you don't specify dataType, it is most probably a string. Because ("false" == false) is false

Do this:

success: function(data) {
        if (data == "false") {
            nom = "whay";
        }
    }

Also, alert should be in success handler. Because A in Ajax means Asynchronous

Amit Joki
  • 58,320
  • 7
  • 77
  • 95
0

Ajax is an asynchronous request, if you put the alert outside the success event, it wont wait for the success event to happen. So it will alert the previous value. So try like this

$.ajax({ type: "POST", url: "micro/wave.php",
data: { username: "some string" },
success: function(data) {
    if (data == false) {
        nom = "whay";

    }
  alert(nom);
}
});
Anoop Joshi P
  • 25,373
  • 8
  • 32
  • 53
0

There are couple of things that could be going wrong...

You are declaring variable somewhere where it' not created properly.

You are forgetting that ajax is async by default so alert function runs before success function... you can change that though.

You success function only runs if request is successful not when there is anything wrong...if you are expecting it to fail then that function won't execute use .done instead.

Muhammad Umer
  • 17,263
  • 19
  • 97
  • 168