Skip to content
Advertisement

Submit Laravel form using JavaScript

I have an HTML form that I currently submit using the form action attribute and a php script. The post request is successful, but it reloads the page, and I want to avoid that. The project uses Laravel/Blade PHP templates.

<form 
  id="update-form" 
  method="post"
  action="{{ route('update', ['id' => $user['id']]) }}"
>
@csrf
...
</form>

<button type="submit" form="update-form">Submit</button>

To prevent page from reloading, I would like to send the post request using JavaScript and use preventDefault(). I tried to use fetch, but as I am not familiar with Laravel I don’t understand which parameter I should send. For example, what is the body?

There are lots of posts on that subject, but most are outdated and result in jQuery solutions, which is not an option for me.

Here is what I tried:

document.querySelector('#update-form').addEventListener('submit', (e) => {
  e.preventDefault();
  fetch("{{ route('update', ['id' => $user['id']]) }}", { 
    method: 'post'
  }).then(() => console.log('success'));
});

Advertisement

Answer

You can use FormData object to get form field and values then send it with fetch in body field.

FormData takes <form></form> element as first param and parses its fields and values

document.querySelector('#update-form').addEventListener('submit', (e) => {
  e.preventDefault();
  var formData = new FormData(e.target);
  fetch("{{ route('update', ['id' => $user['id']]) }}", { 
    method: 'POST',
    body: formData
  }).then(() => console.log('success'));
});
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement