VeRJiL's avatar

Sending file with some other inputs via JS Fetch API

I am trying to send a file with some other inputs to a LARAVEL project. the problem is that when I use body: JSON.stringify(data) , the File is an empty array when I dd(request()->all(). I have tried to remove the "Content-Type": "application/json", but then the whole request()->all() and $_POST is empty. by the way I am not using data = new FormData() and I am creating my data manually (I mean I loop through every element in the form and create an array. this is done because I want to send inputs with the array name to be the actual array when sending to a php endpoint exactly like what HTML does <input name="facilities[]" id="input-1"> <input name="facilities[]" id="input-2">).

0 likes
5 replies
Tray2's avatar

Check this

const formData = new FormData();
const fileField = document.querySelector('input[type="file"]');

formData.append('username', 'abc123');
formData.append('avatar', fileField.files[0]);

fetch('https://example.com/profile/avatar', {
  method: 'PUT',
  body: formData
})
.then(response => response.json())
.then(result => {
  console.log('Success:', result);
})
.catch(error => {
  console.error('Error:', error);
});

It's straight from the Fetch APIO docs on MDN

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

1 like
VeRJiL's avatar

Thanks a lot @tray2 . How can I append inputs with array name as an array so php will get the array as it gets from HTML form submit. The file and other inputs are OK and they are working fine, But when there are inputs which have name as an array "<input name="facilities[]" id="input-1"> <input name="facilities[]" id="input-2">", It messes every thing

Tray2's avatar

Facilities will be sent to you as an array. So you should be able to handle it like this in your controller.

foreach($request->facilities as $facility) {
	//do your stuff
}

On the javascript side you can do something this to get the elements

let inputs = document.querySelectorAll("#formIDHere input[name='facilities[]']");

and then loop through then to create the array.

1 like
VeRJiL's avatar

Allright, so this is what I am going to do: 1. create FormData() object and pass the file input and then 2. loop through my inputs and create an array and append that array to the FormData(). Am I right ?

Please or to participate in this conversation.