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');
        }
      }
    });
  }
}
3
  • Whats with the down vote man? I dont get it Commented Sep 7, 2018 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. Commented Sep 7, 2018 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: stackoverflow.com/questions/37521320/… Commented Sep 7, 2018 at 18:44

1 Answer 1

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?.

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

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.