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){
}
});
});
});
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With