1

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?

1
  • 2
    Are you sure? Or do you assume? Because the if(deleted) return true will be executed before the Ajax callback is executed due to the asynchronous nature of Ajax. Hence: Have you checked the value with a debugger? Commented Oct 2, 2010 at 5:56

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

Comments

0
$("#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.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.