简体   繁体   中英

javascript not working in proper order if-else

I have form which validate duplicate name while saving and i have handling using webapi. the following is a sample function which calls by onclick="return validateName()" from an button click.

function validateName() {
    var nam = $('#frmeditCategory input[id="Name"]').val();
    var result = false;
    $.ajax({
        type: "POST",
        url: "/Admin/CategoryName",
        data: { Name: "test"},
        dataType: "json",
        success: function (response) {
            if (response.message == true) {
                alert("Category already exists.");
                result = false;
                alert(0);
                return false;
            }
            else {
                result = true;
                alert("1");
                return true;
            }
        },
        error: function (xhr, ajaxOptions, thrownError) { alert("some error occured"); result = false; }
    });
    alert("2");
    return false;
}

Here alert("2"); executes first and then ajax is working. I was confused so much and i dont know what im doing wrong. please help me guys!!!

alert("2") would need to be put inside of a $.ajax s promise callback:

$.ajax({
    type: "POST",
    url: "/Admin/CategoryName",
    data: { Name: "test"},
    dataType: "json",
    success: function (response) {
        if (response.message == true) {
            alert("Category already exists.");
            result = false;
            // Why are the following here, they will never get called?
            // alert(0);
            // return false;
        } else {
            // Why is this line here, you never use it?
            // result = true;
            alert("1");
            return true;
        }
    },
    error: function (xhr, ajaxOptions, thrownError) {
        alert("some error occured");
        result = false;
    }
}).done(function () {
    alert("2");
});

set async to false, this will execute the rest of the code after ajax call is complete

  $.ajax({
        type: "POST",
        url: "/Admin/CategoryName",
        data: { Name: "test"},
        dataType: "json",
        async: false,
        success: function (response) {

            if (response.message == true) {
                alert("Category already exists.");
                result = false;
                alert(0);
                return false;
            }
            else {
                result = true;
                alert("1");
                return true;
            }
        },
        error: function (xhr, ajaxOptions, thrownError) { alert("some error occured"); result = false; }
    });

That ajax call is an asynchronous request. What happens is that when you call the method you are starting the request. However, the request may take time to finish, until you get the data from the server, or an error occurs.

The function inside the ajax is executed when the data arrives from the server, and that is why this alert is only done after the alert("2");

Ajax calls are by default asynchronous, meaning code execution doesn't halt waiting for the ajax call to return but instead continues and reaches your alert(2) statement long before the http request returns and your ajax callback is invoked.

You can also perform synchronous ajax calls but that is usually not a good idea as other things will freeze until the call returns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM