0

I have a function called this.create()

this.create = function() {
  var validate = this.validate();

  if (validate === false) {
    return;

  } else if (document.getElementById("nameID").value == "") {

    alert("Enter an ID");
  } else {
    this.runMapping();

    $.post('http://*************', {

    }, function(data) {

      var results = $.parseJSON(data);

      if (results.status == "fail") {
        alert('FAILED');
      } else {
        ID = (results.data[0].nameID);

        alert("SUCCESS");
        this.setDate();


      }
    });
  }
}

And another function called this.setDate():

this.setDate = function() {
  alert("In date");

  $.get('http:**********',
    function(data) {
      var results = $.parseJSON(data);
      date = (results.data[0].date);
      return;
    }
  )
}

Now, if I put this.setDate() on its own button it works fine, but it refuses to run when this.create() is called, even though alert("SUCCESS") is alerted in the this.create() function.

I should add that I am relativity new to JS, so please excuse me if this is an easy mistake I am making. I also note that this.runMapping() is working fine in this.create().

Michael Hutter
  • 652
  • 6
  • 24
ScoutEU
  • 2,738
  • 10
  • 33
  • 64
  • 5
    In your callback function, `this` refers to the callback function, not to the outer object. Use an arrow function, or use a variable to hold a reference to the outer object. – Robby Cornelissen May 16 '18 at 07:29
  • Or dont work with the context at all if possible. And please have a look at your consope, it will say something like "cannot call `undefined` at..." – Jonas Wilms May 16 '18 at 07:32
  • Thank you guys, that was the problem! – ScoutEU May 16 '18 at 07:34

1 Answers1

2

This is because this is now context of the function where you are calling your this.setDate(); and there is no such function in it.

Use arrow function or save this reference to a variable and call your function what that reference like

var that = this;
 this.create = function() {
   ....
    that.setDate()
   ...
Muhammad Usman
  • 9,463
  • 18
  • 35