M
M
Maxim Kalinin2020-11-04 00:49:00
PHP
Maxim Kalinin, 2020-11-04 00:49:00

How to submit a form using fetch, process in php and return a response?

Actually, a method is written in React that is executed as soon as the user submits the form:

handleSubmit(e){
    e.preventDefault();
    let callBack = new FormData(e);
    fetch('http://127.0.0.1', {
      method: 'POST',
      headers: {
        "Content-Type": "multipart/form-data"
      }, 
      body: callBack
    }).then(res => res.json()).then((result) => {console.log('Result = ' + result)}, (error) => {console.log('Error = ' + error)});
  }


PHP handler (it is running on OpenServer, and from 127.0.0.1 it redirects to the handler file):
<?php
$data = $_REQUEST["callBack"];
print_r($data);
?>


For some reason, after submitting the form, I get an error:
Modal.js:45 Uncaught TypeError: Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alex, 2020-11-04
@MaximAr1es

`e` in this case is the event object. `FormData` expects an HTML FORM element. Try taking `e.target`.
let callBack = new FormData(e.target);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question