Kiow
Kiow

Reputation: 880

Laravel vue axios is action method and csrf needed for ajax forms

I am posting a ajax from in Laravel using axios and vue, I have a @click="postData" button in the form that toggles a axios post request:

postData() {
      axios({
          method: 'post',
          url: appJS.base_url + '/comment',
          responseType: 'json',
          data: comData
        })
        .then(function(response) {

        })

But do I still need to add the action, method and csrf to my form?

<form action="{{ url('/comment') }}" method="POST">
{{ csrf_field() }}
</form>

vs

<form></form>

Everything works fine just using <form></form> but I wonder if there are any pros/cons?

I am making a ajax call in the background since I dont want the whole page to reload

Upvotes: 0

Views: 2423

Answers (2)

you can using event form in vuejs, you need't using ajax, you can try the following code, but if laravel + vuejs, need add Enable CORS for a Single Route in laravel:https://gist.github.com/drewjoh/43ba206c1cde9ace35de154a5c84fc6d

export default{
        data(){
            return{
                title:"Form Register",
            }
        },
        methods:{
           register(){
                this.axios.post("http://localhost:8888/form-register",this.formdata).then((response) => {
                       console.log(response);
                      
                  });
                    
            },
 
        }
    }
 <form action="" method="post" v-on:submit.prevent="register">
    <div class="panel-heading">{{title}}</div>
    <div class="form-group">
      <button type="submit" class="btn btn-danger">Register</button>
      <button type="reset" class="btn btn-success">Reset</button>                  
    </div>
 </form>
 
 

Upvotes: 0

Hedegare
Hedegare

Reputation: 2047

You definitely don't need action and method attributes on form tag, because they are already defined on your axios call.

As for the csrf_field(), you probably still need it, because Laravel has a preconfigured middleware called VerifyCsrfToken. But it depends if you use it or not.

Upvotes: 1

Related Questions