0

I have a method like this:

var isNameUnique = false;

function ValidateName() {

        var url = "/SomeRules/CheckIfNameExists/";

        var request = $.ajax({
            url: url,
            method: "GET",
            data: { sName: name},
            dataType: "JSON"
        });
        request.done(function (result) {
            if (result.doesNameExists) {
                alert("Name Already Exists!");
                console.log("Name Already Exists!");
            }
            else {
                isNameUnique = true;
                console.log("Name is unique!");
            }

        });

        request.fail(function (jqXHR, textStatus) {
            console.log(textStatus);
            alert("Request failed.");
        });

    console.log("Exiting ValidateName()");
}

This is called like so:

function CreateNewUser() {
    ValidateName();
    console.log(isNameUnique);
    if(isNameUnique){
     // do stuff
    }
}

When I run the application I have these in the console in this order:

  1. Exiting ValidateName()
  2. false
  3. Name is unique!

When it's printing the 3rd console I expect 'isNameUnique' to be set to true. But that's not happening!!! What am I doing wrong?

Thanks in advance.

Codehelp
  • 4,157
  • 9
  • 59
  • 96
  • You mean that the `console.log` in your `createNewUser` should say `true`? That is not going to happen. That console.log gets triggered before your ajax call is done. – putvande Jun 01 '15 at 10:30

2 Answers2

0

By default every Ajax request is asynchronous, means code next to Ajax call will not wait for the completion of Ajax call. So what you need to do is, make your Ajax call synchronous, so that next lines of code will execute only after completion of ajax call.

To make your ajax call synchronous add following option in ajax Setting:

async : false

For more info check this documentation and read about async setting.

Puneet
  • 2,051
  • 9
  • 17
  • Puneet, using async:false results in this error 'Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.' – Codehelp Jun 01 '15 at 10:41
0

That happens when you start using async. Your variable isNameUnique gets assign the value but long after you call console.log(isNameUnique);. The best way to tackle that is to make the function ValidateName returning a promise and chain on it.

defectus
  • 1,947
  • 2
  • 16
  • 21