JQuery bind on Ajax success

10,547

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.

Share:
10,547

Related videos on Youtube

shubham
Author by

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, 2022

Comments

  • shubham
    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 use bind here?

  • shubham
    shubham about 9 years
    Sorry i didnt get this.Would you please elaborate
  • Scimonster
    Scimonster about 9 years
    If you don't call bind, this inside the callback will be the wrong thing.
  • angelia
    angelia over 8 years
    I 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