开发者

Jquery AJAX: How to Change button value on "success"?

I have multiple buttons on one page. Upon click, I track the button id, send the button value to backend php code that returns me updated value by changing the database. I am able to get back everything i need except this: Setting the button value on success!! This is the code i'm using:

$(document).ready(function(){
    $("input[type='button']").click(function(){
        var selected = $(this).attr("id");
        var val = prompt("Enter new value",0);
                    $.ajax({
                    url:'updateCostItems.php',
                    data:{to开发者_如何学Pythonupdate:selected, updatewith:val},
                    type:'GET',
                    dataType:'json',
                    success:function(json){
                        $(this).val(json.update);
                    },
                    error:function(xhr, status){
                        alert("Problem");
                    },
                    complete:function(xhr, status){

                    }
                });
        });
});


I think this is not correct, because the callback is run in the global scope.

Untested, but try just before $.ajax to write var $this = $(this) and then in your callback use $this.val(json.update)


Edit: Updated code snippet to ensure local $this by declaring with var. Other posts suggest using var button = $(this) which is probably better in bigger projects where keeping track of the variables is more challenging - but all the answers are the same really.


The problem is that 'this', inside the ajax request, points to the xhr object, not the button. You should store the reference to the button prior to do the call, like var button = $(this); and later updating it button.val(json.update);


Store the button in a local variable in the outer loop, then refer to that variable in the inner scope of the success handler:

$(document).ready(function(){
    $("input[type='button']").click(function(){
        var $btn = $(this)
        var selected = $btn.attr("id");
        var val = prompt("Enter new value",0);
        $.ajax({
            url:'updateCostItems.php',
            data:{toupdate:selected, updatewith:val},
            type:'GET',
            dataType:'json',
            success:function(json){
                $btn.val(json.update);
            },
            error:function(xhr, status){
                alert("Problem");
            },
        });
    });
});


$(this) will not refer to the button at the time the success function is called. You will need to pass the button (or the button's id) along as a parameter to your callback. Storing a single global variable is not sufficient since you could potentially click on a 2nd button before the first ajax call returns.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜