-
-
Save johanneslamers/999dcf8de3b994a1ccb005a4935b9e5d to your computer and use it in GitHub Desktop.
vue directive for ajax submits on laravel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<form method="POST" | |
action="/posts/3" | |
v-ajax complete="Okay, the post has been deleted." | |
> | |
{{ method_field('DELETE') }} | |
{{ csrf_field() }} | |
<button type="submit">Delete Post</button> | |
</form> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.15/vue.min.js"></script> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/0.6.1/vue-resource.min.js"></script> | |
<script src="/js/app.js"></script> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Vue.directive('ajax', { | |
params: ['complete'], | |
bind: function () { | |
this.el.addEventListener( | |
'submit', this.onSubmit.bind(this) | |
); | |
}, | |
onSubmit: function (e) { | |
var requestType = this.getRequestType(); | |
this.vm | |
.$http[requestType](this.el.action) | |
.then(this.onComplete.bind(this)) | |
.catch(this.onError.bind(this)); | |
e.preventDefault(); | |
}, | |
onComplete: function () { | |
if (this.params.complete) { | |
alert(this.params.complete); // Use pretty flash message instead. | |
} | |
}, | |
onError: function (response) { | |
alert(response.data.message); // Use pretty flash message instead. | |
}, | |
getRequestType: function () { | |
var method = this.el.querySelector('input[name="_method"]'); | |
return (method ? method.value : this.el.method).toLowerCase(); | |
}, | |
}); | |
new Vue({ | |
el: 'body', | |
http: { | |
headers: { | |
// You could also store your token in a global object, | |
// and reference it here. APP.token | |
'X-CSRF-TOKEN': document.querySelector('input[name="_token"]').value | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment