Steven
Steven

Reputation: 75

Javascript/JQuery: Variable Undefined After Performing Ajax

In the console.log, I can see that this.id is undefined after the Ajax call. I would still like to use the id of .home after that. I know I can again still perform $('.home').attr('id') in the .done section but that would be repeating the same code again. Is there a better/more efficient way of calling this.id (the id of .home) inside .done? I have placed the JavaScript file at the bottom of the <body> tag.

JQuery

$(".home").submit(function(e) {
  e.preventDefault();
  e.stopPropagation();
  var sendData = {
        //Some data
      };
  var url = "/home" + this.id;
  $.ajax({
      url: url,
      type: "POST",
      contentType: "application/json",
      data: JSON.stringify(sendData)
  }).done(function(result){
      //This shows undefined.
      console.log(this.id)
  })
});

Upvotes: 0

Views: 67

Answers (2)

Martin Vich
Martin Vich

Reputation: 1082

Problem is that this behaves little bit differently than in other languages. You have two options:

Either you can put id into variable

var id = this.id;
$.ajax({
  url: url,
  type: "POST",
  contentType: "application/json",
  data: JSON.stringify(sendData)
}).done(function(result){
  console.log(id)
})

or you can bind this

var onDone = function(result) {
  console.log(this.id)
}
$.ajax({
  url: url,
  type: "POST",
  contentType: "application/json",
  data: JSON.stringify(sendData)
}).done(onDone.bind(this));

this way your this will stay the same

Upvotes: 3

Striped
Striped

Reputation: 2547

You need to store your id before the ajax request like :

$(".home").submit(function(e) {
  e.preventDefault();
  e.stopPropagation();
  var sendData = {};
  var id = this.id;
  var url = "/home" + id;
  $.ajax({
      url: url,
      type: "POST",
      contentType: "application/json",
      data: JSON.stringify(sendData)
  }).done(function(result){
      console.log(id)
  })
});

Upvotes: 2

Related Questions