JQuery bind on Ajax success
Solution 1
You need to call bind()
in order to force your callbacks context (this
) to be the right thing. Otherwise, it is called in the global context by default (apparently, jQuery calls it with a context of the jqXHR object). bind()
sets the context of your function to whatever this
is supposed to be.
Solution 2
@shubham, it's the JavaScript syntax to use current this in your callback function as you mentioned in:
success: function(data){
this.setState({data: data});
}
First argument of bind()
function will act as this in calling function, you should go through apply()
and call()
functions as this would be helpful for you.
Solution 3
I suppose your code from React. Because recently I encounter similar issue dealing with React.
Back to your question. I think the bind
is play a transform function. Code as follow:
componentDidMount: function() {
var _this = this;
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function(data) {
_this.setState({data: data});
}
});
},
is equal to:
componentDidMount: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function(data) {
this.setState({data: data});
}.bind(this)
});
},
As so for, I think you can understand what is the bind function and why using bind
to achieve it.
Related videos on Youtube
shubham
Working as a JS developer for more than 5 years. Exposed to working with react-native and react with the latest libraries and that too considering the aftereffects and performance analysis. Open to collaborate for open source projects. React to me at LinkedIn.
Updated on October 19, 2022Comments
-
shubham over 1 year
Why do we call bind on AJAX
success
calls?Take a look at this code:
$.ajax({ url: myurl, dataType: 'json', success: function(data){ this.setState({data: data}); }.bind(this) });
If we don't call
bind
, then does it makes any difference or there is an advantage to usebind
here? -
shubham about 9 yearsSorry i didnt get this.Would you please elaborate
-
Scimonster about 9 yearsIf you don't call bind,
this
inside the callback will be the wrong thing. -
angelia over 8 yearsI agree with Scimonster.bind() sets the context of your function to whatever this is supposed to be,or your function will give an error like this:Uncaught TypeError: this.setState is not a function