Home > Blockchain >  AJAX POST request to a PHP server: Invalid request (Malformed HTTP request) on console and net::ERR_
AJAX POST request to a PHP server: Invalid request (Malformed HTTP request) on console and net::ERR_

Time:01-11

I have the files test.html, test.js and test.php in my directory. I am trying to send some data to my backend, which should be dealt with by test.php. I run my server using PHP's built-in webserver with the command php -S 0.0.0.0:8080 -t test-server/.

Here's a simplified demonstration, whenever I click "submit", it should send the data to my php server. The JS:

window.onload = () => {
    submit = document.getElementById('submit');
    submit.addEventListener('click', () => {
        const xhttp = new XMLHttpRequest();
        xhttp.onload = function() {
            window.location.replace("test.php");
        }
        xhttp.open("test.php", "POST", true);
        xhttp.setRequestHeader('Content-type', 'application/json; charset=utf-8');
        var data = {'name':'foo'};
        xhttp.send(JSON.stringify(data));
    });
}

And here's my PHP:

<?php 
    echo "foo";
    var_dump($_POST);
?>

However, the data isn't being sent, and the xhttp.onload never works. The error Invalid request (Malformed HTTP request) shows up on my server and the error net::ERR_EMPTY_RESPONSE pops up in chrome's developer tools.

What am I doing wrong?

CodePudding user response:

The xhttp.open uses this signature:

open(method, url, async, user, password)

You just inversed method and url in your call.

More informations: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/open

  • Related