views:

69

answers:

2

I have a external js file handling deleteing 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?

+3  A: 

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

meder
A: 
$("#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.

Jichao
Why do you need to return true or false anyway? What happens if it was not deleted? Try to avoid synchronous requests.
Felix Kling