JQuery AJAX: How do I change the value of a button to "success"?

I have several buttons on one page. After clicking, I will track the button identifier, send the button value for the php backup code, which returns me the updated value by changing the database. I can return everything I need, except for this: setting the button value on successful execution! 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){ } }); }); }); 
+6
source share
4 answers

I think this incorrect because the callback is fired in the global scope.

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


Edit: Updated code snippet to provide local $this by declaring with var. Other posts suggest using var button = $(this) , which is probably better in large projects where tracking variables is more complicated, but all the answers are actually the same.

+4
source

The problem is that the 'this' inside the ajax request points to the xhr object, not the button. Before calling you must save the link to the button, for example var button = $(this); and then update its button.val(json.update);

+1
source

Save the button in a local variable in the outer loop, then refer to this variable in the inner area 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"); }, }); }); }); 
+1
source

$ (this) will not refer to the button at the time the success function is called. You will need to pass the button (or button id) as a parameter to your callback. Storing one global variable is not enough, since you can press the second button before the first ajax call returns.

0
source

Source: https://habr.com/ru/post/886501/


All Articles