I am trying to change some old code which uses onclick so that I an use the $(this). The problem is that $(this) is not working when inside the success. Is there anyway to do this without setting it as a var.
$('.addToCart').click(function() { $.ajax({ url: 'cart/update', type: 'post', data: 'product_id=' + $(this).attr("data-id"), dataType: 'json', success: function(json) { if (json['success']) { $(this).addClass("test"); } } }); });
ajax post method. The reason was my response was not in the JSON format so there was no need for the dataType: 'json' line in the submit method. In my case, the returned response was in text format that's why it was not going to success event. Solution: Remove dataType: 'json' line.
success and Error : A success callback that gets invoked upon successful completion of an Ajax request. A failure callback that gets invoked in case there is any error while making the request.
success() only gets called if your webserver responds with a 200 OK HTTP header - basically when everything is fine. However, . complete() will always get called no matter if the ajax call was successful or not - maybe it outputted errors and returned an error - . complete() will still get called.
Inside the callback, this
refers to the jqXHR
object of the Ajax call, not the element the event handler was bound to. Learn more about how this
works in JavaScript.
If ES2015+ is available to you, then using an arrow function would probably be the simplest option:
$.ajax({ //... success: (json) => { // `this` refers to whatever `this` refers to outside the function } });
You can set the context
option:
This object will be made the context of all Ajax-related callbacks. By default, the context is an object that represents the ajax settings used in the call (
$.ajaxSettings
merged with the settings passed to$.ajax
). (...)
$.ajax({ //... context: this, success: function(json) { // `this` refers to the value of `context` } });
or use $.proxy
:
$.ajax({ //... success: $.proxy(function(json) { // `this` refers to the second argument of `$.proxy` }, this) });
or keep a reference to the value of this
outside the callback:
var element = this; $.ajax({ //... success: function(json) { // `this` refers to the jQXHR object // use `element` to refer to the DOM element // or `$(element)` to refer to the jQuery object } });
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