0

Hey guys I am using vuejs and ajax to send formData and return a json response. There's a json response comes though however I cant assign it to the vue data object. Any ideas as to why? Heres my method. I know the function is firing as it hits the other page and returns json data in the console. Message, nameExists, and error wont assign even though all our in the vue data property and is spelled correctly.

addTemplate: function() {
  this.sub = true;
  this.itemName = this.itemName.trim();
  var addTemplateForm = document.getElementById("addTemplateForm");
  var fd = new FormData(addTemplateForm);
  if (this.validItemName == true /* etc...*/) {
    $.ajax({
      url:'addTemplateBackend.php',
      type:'POST',
      dataType: 'json',
      data: fd,
      contentType: false,       // The content type used when sending data to the server.
      cache: false,             // To unable request pages to be cached
      processData:false,        // To send DOMDocument or non processed data file it is set to false
      error: function(data){
        this.message = data.message;
        alert('error');
      },
      success: function(data){
        alert('success');
        this.error = data.error;
        this.message = data.message;
        console.log(data);
        this.nameExists = data.nameExists;
        if(data.success == true){
          $('#successModal').modal('show');
        }
      }
    });
  }
}
Boussadjra Brahim
  • 82,684
  • 19
  • 144
  • 164
codernoob6
  • 61
  • 1
  • 6
  • Whats with the down vote man? I dont get it – codernoob6 Sep 07 '18 at 18:36
  • the close request is due to *off topic because unclear what desired result is*. Can you clarify what you would like it to do? I noticed though you have `$('#successModal').modal('show');` which looks like jquery code, not vue, You may need to include your template too. – Daniel Sep 07 '18 at 18:41
  • 2
    the way to update the vue's data object, you would usually use `this.myVar` to assign a variable to `data:{myVar:null}`, however, because you're using a callback function to define success action, it is important to note that the scope gets lost, so you need to either use `context:this`, `.bind(this)` or `var self = this;` inside the main function and then use `self.myVar` to assign. link with more detail: https://stackoverflow.com/questions/37521320/javascript-how-to-bind-this-inside-an-ajax-call-to-the-object-literal – Daniel Sep 07 '18 at 18:44

1 Answers1

1

You need to either bind this:

success: function (data) {
  this.message = data.message;
}.bind(this)

or use ES6 "fat arrow" syntax:

success: data => {
  this.message = data.message;
}

See How does the "this" keyword work?.

Decade Moon
  • 32,968
  • 8
  • 81
  • 101