Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

ajax

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:{toupdate:selected, updatewith:val},
                    type:'GET',
                    dataType:'json',
                    success:function(json){
                        $(this).val(json.update);
                    },
                    error:function(xhr, status){
                        alert("Problem");
                    },
                    complete:function(xhr, status){

                    }
                });
        });
});
like image 962
Aakash Goel Avatar asked Apr 22 '11 20:04

Aakash Goel


2 Answers

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.

like image 147
Billy Moon Avatar answered Sep 19 '22 17:09

Billy Moon


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);

like image 37
morgar Avatar answered Sep 22 '22 17:09

morgar