Jichao
Jichao

Reputation: 41805

Why JavaScript global variable is not global?

I have a external js file handling deleting some element. According to the result, I would determine whether I need to refresh the page or not.

var deleted = 0; // first assume not deleted 

$(function() {
    $("#action a.action-delete").click(function() {
        var id = $(this).parent().parent().attr("id");
        $.get("modify-sale.php", { "id" : id, "action" : "delete" }, function (data) { deleted = 1;  }, "text");
        if (deleted) return true; // if success then refresh
        else return false; // else does not refresh
    });

No the problem is I could not change the global variable deleted in the jQuery event handler. I can assure that the delete action is success, but this variable just does not change its value to 1.

Why?

Upvotes: 1

Views: 507

Answers (2)

Jichao
Jichao

Reputation: 41805

$("#action a.action-delete").click(function() {
    var id = $(this).parent().parent().attr("id");
    $.ajax({
        "url" :  "modify-sale.php",
        "type" : "GET",
        "data" : { "id" : id, "action" : "delete" },
        "dataType" : "text",
        "async" : false,
        "success" : function(data) {
            if (data == 'success') {
                $("#msg").text("delete success").show();
                $("#msg").fadeOut(1000);
                deleted = 1;
            } else {
                $("#msg").text("delete failed, plesase try later").show();
                $("#msg").fadeOut(5000);
            }
        },
        "error" : function() {
            $("#msg").text("delete failed, please try later").show();
            $("#msg").fadeOut(5000);
        }
    });
    if (deleted) return true;
    else return false;
});

I fixed it with the async set to synchronized.

Upvotes: 0

meder omuraliev
meder omuraliev

Reputation: 186552

Ajax is asynchronous, so it will set the deleted variable after you do the if else check. Try putting the check in the callback.

Upvotes: 5

Related Questions