4

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'));
});

2 Answers 2

6

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'));
});
Sign up to request clarification or add additional context in comments.

Comments

0

When a form is submitted with JavaScript to a route action, e.g. <form action={{route('something')}}> The data(form inputs) are passed as a {$key => $value} object. Therefore, in your controller, you can get the data individual input field by the name attribute of input.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.