Fetch API With HTML Form & PHP



Hey you... FETCH ME THAT JSON!

We can jQuery AJAX or a straight up XMLHttpRequest. Now we can use the new Fetch API. Here is a short example on how to send data from an HTML form to PHP using the Fetch API. Let's have a play with it...

First we'll create a simple HTML form with 2 inputs and include scripts.js which we'll create in the next step.

HTML (index.html)

<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>FETCH JS</title>
</head>

<body>
    <form id='form'>
        <input type='text' placeholder='Name' name='name' required>
        <input type='email' placeholder='Email' name='email' required>
        <button type='submit'>Submit</button>
    </form>

    <script src="scripts.js"></script>
</body>

</html>

Now let's throw ourselves into the Javascript. Async ensures that the function returns a promise. Await waits for the promise to come through before returning its results. If there's an error we can catch it.

JS (scripts.js)

async function sendData(data, url) {
  try {
    const request = await fetch(url, {
      method: 'POST',
      body: data
    });

    const result = await request.json();
    console.log(result);
  } catch (error) {
    console.error(error);
  }
}

const form = document.getElementById('form');

form.addEventListener('submit', function(e) {
  e.preventDefault();
  var data = new FormData(document.forms.form);
  sendData(data, 'post.php');
});

Rolling onto the backend to pick up the form data sent from JS we'll check if the required fields are present and return some JSON with the results.

PHP (post.php)

<?php
$result = ['result' => false];

if (isset($_POST['name']) && isset($_POST['email'])) {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $result['result'] = true;
    $result['name'] = $name;
    $result['email'] = $email;
}

echo json_encode($result);

Thanks for reading. x

Resources