Skip to content

AJAX POST request to a PHP server: Invalid request (Malformed HTTP request) on console and net::ERR_EMPTY_RESPONSE on chrome dev tools

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 -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() {
        }"test.php", "POST", true);
        xhttp.setRequestHeader('Content-type', 'application/json; charset=utf-8');
        var data = {'name':'foo'};

And here’s my PHP:

    echo "foo";

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?



The uses this signature:

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

You just inversed method and url in your call.

More informations:

User contributions licensed under: CC BY-SA
6 People found this is helpful