Post ajax method for Laravel with Fetch API | Vanilla JS

Barbara Bombachini
Code Snippets
Published in
1 min readMar 21, 2018

I’ve had a hard time finding an example of making a post request on Laravel through fetch API as most examples are using jQuery only to make it shorter.

So I hope this eventually help someone.

Firsts things first, Laravel requires a token to check for Cross-Site Request Forgery . So you should have a metatag in the header with the token — as explicit on Laravel’s documentation.

<meta name="csrf-token" content="{{ csrf_token() }}">

Then, you need to send it all together with your post method.

//Select token with getAttribute
let token = document.querySelector(‘meta[name=”csrftoken”]’).getAttribute(‘content’);
//Select input values with the data you want to send
let name = document.querySelector(‘input[name=”name”]’).value;
let number = document.querySelector(‘input[name=”number”]’).value;
//Define your post url
let url = '/admin/part/store';
//Define redirect if needed
let redirect = '/admin/part/list';
//Select your form to clear data after sucessful post
let form = document.querySelector('#addPart');

And then make a call to the API. Some tests with different content on headers thrown me some errors.

fetch(url, {
headers: {
"Content-Type": "application/json",
"Accept": "application/json, text-plain, */*",
"X-Requested-With": "XMLHttpRequest",
"X-CSRF-TOKEN": token
},
method: 'post',
credentials: "same-origin",
body: JSON.stringify({
name: name,
number: number
})
})
.then((data) => {
form.reset();
window.location.href = redirect;
})
.catch(function(error) {
console.log(error);
});
}

It would be awesome to have some syntax highlight in here, han?!

--

--