Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<?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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading