Isn't fetch an API. Found https://scotch.io/tutorials/how-to-use-the-javascript-fetch-api-to-get-data
Can somebody help me with fetch() function
I am trying to use fetch function in vanilla js to call in method in my controller. I am using POST method. Unfortunately $request from Illuminate/App/Request keep coming empty. My question does Laravel support fetch function?
Fetch is Javascript API. Try this https://stackoverflow.com/questions/33439030/how-to-grab-data-using-fetch-api-post-method-in-php
Thank you guys. I did manage to get it work with jQuery. And with form. Problem is that when I use post method with fetch api, and call controller in laravel, Request come empty. Is there some trick in laravel, that I am not aware, or there is no support for it in laravel?
This is how to make a POST request using the fetch api.
const url = 'https://randomuser.me/api';
// The data we are going to send in our request
let data = {
name: 'Sara'
}
// The parameters we are gonna pass to the fetch function
let fetchData = {
method: 'POST',
body: data,
headers: new Headers()
}
fetch(url, fetchData)
.then(function() {
// Handle response you get from the server
});
Should then be able to access it, and to double check, you can use request()->all()
Thanks for help, but it didn't work. request()->all() is empty. Any request I made with fetch is empty.
Interesting.
As far as I know, the fetch API isn't all that popular. Most people use jQuery, or Axios. Axios is brilliant.
That could explain things little more.
I suspect that Illuminate\Http\Request laravel class doesn't have method that is in-charge with fetch API, but I can't confirm or deny it; and that's why I am asking. If fetch isn't popular, it is quite possible, they didn't bother installing it.
I am finishing php course, and we only did form and fetch as ways to call server, and I am under impression that fetch is next new thing. That is why I am trying to implement the fetch.
Stick with axios. It's used widely across the Laravel community among other communities such as Java, python etc.
The request class won't have a method for the fetch API, as that's now how it works. Fetch is essentially a replacement for the legacy XHR Javascript API
fetch() works just fine. remove the headers from the request and let the browser manage it. here's my snippet to handle it - no need for dependencies such as jQuery or axxios. Sorry, bad advise :)
I left out the event and I wrapped the fetch api in a class Http.
const form = document.getElementById('form'),
formData = new FormData(),
messages = document.getElementById('message');
const inputs = form.querySelectorAll('[name]');
for (const input of inputs)
formData.append(input.name, input.type === 'file' ? input.files[0] : input.value);
const id = formData.get('id'),
url = form.getAttribute('action');
Http.method = 'POST';
if (id)
formData.append('_method', 'PUT');
Http.body = formData;
Http.request(url).then(response =>
{
});
@artcore Fetch API is still missing core fundamental features like request cancelling, interception, transformations etc.
The standard library that is used nowadays is Axios. It's an extremely light-weight package, yet satisfies every solution you'll ever need.
Of course, you're free to use Fetch API, I have done so for simple GET requests myself, but respectfully, it wasn't bad advice.
Most people use frameworks nowadays (yourself included), and these often ship out of the box with standard, well tested packages for a reason, and axios is one of them. Fetch has yet to prove it's worth switching to full-time; when/if it does, it's likely we'll stop using axios, just like all other previous packages
You're right and I take back the 'bad advise' remark! It was 7am for me, apologies... imho one package or dependency less is always the priority. And it's better to understand why something didn't work then to just slap a package to handle it for you. Packages always have their own interfaces covering up the actual underlying methodology and they introduce their own issues, so you end up researching the facade instead of the actual basics.
My teacher find the solution; @csrf (must be blade.php)
let options={ method: "POST", body: JSON.stringify(data), headers: { 'X-CSRF-TOKEN': document.querySelector('input[name="_token"]').value, 'Content-Type': 'application/json' } }
fetch('url', options).then(res=>res.json())
and now fetch api will work with laravel controller, and it will return data in (Request $request).
@artcore Don't stress :)
@alek101 That's great. Take note tho, each time you use fetch() you'll need to pass all those options again. With axios, you can set the CSRF token automatically, and it'll automatically cast the response to JSON, which means you can simply get on with the request:
axios.post(url, data).then(response => this.response = response.data);
It'll set the headers all behind the scenes, since it's configured in resources/js/bootstrap.js by default.
EDIT: I realize it sounds biased, but I just need to state that fetch is under-developed, and doesn't yet meet the requirements of other packages, especially for a native solution.
since I have experience in JavaScript programming, I've achieved it like this & working like a charm
// Wait to load Html DOM
document.addEventListener("DOMContentLoaded", () => {
const button = document.querySelector('#Your-Button');
if (button) {
button.addEventListener('click', buttonClickHandler);
}
// Function to call api
async function buttonClickHandler(e) {
// Get data to submit
const user = document.querySelector('#name').value;
const pass = document.querySelector('#pass').value;
// Call api
try {
const response = await fetch("{{ route('login') }}", {
method: 'post',
body: JSON.stringify({
user: user,
pass: pass,
"_token": "{{ csrf_token() }}",
}),
headers: {
"Content-Type": "application/json",
},
});
if (!response.ok) {
throw new Error("Network response was not OK");
}
const apiResponse = await response.json();
// Handle response here ....
} catch (error) {
// Hanel error
// alert(error.message)
console.error(error);
} finally {
console.log('API call completed');
}
}
});
Please or to participate in this conversation.