Search code examples
javascriptfetch-apiform-data

After sending form with AJAX, the $_POST looks empty


I'm trying to send my form input with AJAX in JS.

The actual code looks like this:

const form = document.querySelector('#login');

form.addEventListener('submit', function (event) {
    event.preventDefault();

    fetch('page.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(new FormData(this))
    })
    .then(response => response.json())
    .then(result => {
        console.log('Success:', result);
    })
    .catch(error => {
        console.error('Error:', error);
    });
});

Issue here, is in my PHP page, the print_r($_POST); returns me something blank.

If needed, the form HTML:

<form id="login">
    <div class="form-group mb-3">
        <input type="email" class="form-control" name="USR_Email" placeholder="Email Address">
    </div>
    <div class="form-group mb-3">
        <input type="password" class="form-control" name="USR_Password" placeholder="Password">
    </div>
    <div class="d-grid mt-4">
        <button type="submit" class="btn btn-primary">Login</button>
        <input type="hidden" name="action" value="login">
    </div>
</form>

Do I missed something ?

Thanks.


Solution

  • The root of the problem is that

    JSON.stringify(new FormData(this))
    

    doesn't output anything.

    There are ways to correctly serialize FormData to JSON, but you would then also need to alter your PHP code to receive the POSTed JSON data correctly.

    A simpler solution is to just take JSON out of the equation, and provide the FormData object directly, which fetch() will automatically URL-encode for you, and which PHP will then automatically parse into the $_POST array for you. You don't particularly need the overhead of JSON in your scenario.

    Just write

    fetch('page.php', {
      method: 'POST',         
      body: new FormData(this)     
    })