Fil Fil - 5 months ago 7
jQuery Question

How to get the value of `submit.preloader_id = "div#some-id";` in `beforesend` method inside ajax?

I have the following code written in javascript,

var submit = {
preloader_id: "",

send:function (form_id) {
var url = $(form_id).attr("action");
$.ajax({
type: "POST",
url: url,
data: $(form_id).serialize(),
dataType: 'json',
success:(result) => {
},
error: function(result) {
// Some errors
},
beforeSend: function() {
console.log(this.preloader_id);
if (this.preloader_id != "") {
run_preloader(this.preloader_id);
}
},
completes: function() {
if (this.preloader_id != "") {
run_preloader(this.preloader_id, 'true');
}
}
});
}
}


and is called like this

submit.preloader_id = "form-id";
submit.send('div#some-id');


The problem is when I tried to get value assigned in
preloader_id
inside this method

beforeSend: function() {
console.log(this.preloader_id); // look if there is id name to fetch
if (this.preloader_id != "") {
run_preloader(this.preloader_id);
}
},


I get undefined,

How to get the value of
submit.preloader_id = "div#some-id";
in
beforesend
method inside ajax?

Answer

The issue is because the scope of this has changed within the beforeSend handler of $.ajax. To fix this, store the reference outside the handler:

var submit = {
  preloader_id: "",

  send:function (form_id) {
    var _this = this; // store here
    var url = $(form_id).attr("action");

    $.ajax({
      type: "POST",
      url: url,
      data: $(form_id).serialize(),
      dataType: 'json',
      success:(result) => {},
      error: function(result) {
        // Some errors
      },
      beforeSend: function() {
        // use here...
        console.log(_this.preloader_id);
        if (_this.preloader_id != "") {
          run_preloader(_this.preloader_id);
        }
      },
      completes: function() {
        // and here...
        if (_this.preloader_id != "") {
          run_preloader(_this.preloader_id, 'true');
        }
      }
    });
  }
}