0

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)
  })
});
1
  • How do you know that 'this.id' exists at all? Have you tested it before the url attempts to use it? I suspect that 'this' in .done is not the same as 'this' when called by the submit method...try console.dir(this) ; in each method to see the contents. Commented Mar 16, 2018 at 7:51

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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)
  })
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.