2

Using ajax and vue.js, i was able to get and display data from an api i created. However, when I try posting to the api, I run into issues. Nothing is showing up in the console, so this issue is particularly complicated for me. The data binding in my form appears to be working and passing into the function when i tinker with alerts within the function. however, no data is being sent.

here is my html :

<form>

  <input placeholder="Enter your Name" v-model="newGuest.name"><br><br>

  <textarea placeholder="Leave a Message" v-model="newGuest.message"></textarea><br><br>

  <button v-on:click="addGuest">Submit</button>

</form>

here is the data setup for newGuest, which is the json binded to the form input fields:

newGuest: {
    name:'',
    message:''
  }

finally, here is the vue.js/ajax code for sending post request:

addGuest: function () {

    var xhp = new XMLHttpRequest()
    xhp.open('POST', apiURL)
    xhp.setRequestHeader("Content-type", "application/json");
    xhp.send(this.newGuest)

    this.newGuest.name = ''
    this.newGuest.message = ''

  }

my get requests using ajax look almost exactly the same, and it is working. So im pretty sure my ajax syntax is correct

2
  • Try to stringify the newGuest object: xhp.send(JSON.stringify(this.newGuest)) Commented Mar 3, 2016 at 5:46
  • omg thank you so much, i tried stringifying it but i must have done it wrong. i first stored it as a variable, then sent that variable using .send Commented Mar 3, 2016 at 7:30

1 Answer 1

2

You should use vue-resource, which is designed to work specifically with VueJS. You won't have the problems that you have now and the functionality is pretty similar to jQuery's AJAX functions:

  this.$http({url: '/someUrl', method: 'GET'}).then(function (response) {
      // success callback
  }, function (response) {
      // error callback
  });

Docs here.

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

2 Comments

i looked into that and decided not to because it would be an extra file and writing ajax is relatively easy. what benefits come from using vue-resource aside from this one?
You can always combine files. I'd say that the benefits are quite obvious - easier syntax (smaller code), easier response/error/general callback handling. The interceptor functionality is pretty great (run X before/after any request). Obviously, if you're making just a few ajax calls in your app, you don't need the additional weight.

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.