简体   繁体   中英

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

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

When a form is submitted with JavaScript to a route action, eg <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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM