Jo Colina
Jo Colina

Reputation: 1914

XMLHttpRequest POST to PHP

I'm having some trouble managing the answers to a simple XMLHttpRequest made on JS to my own server. I have some troubling answers, here's my code:

JavaScript:

function callPHP () {
    var xml = new XMLHttpRequest();
    xml.open("POST", "http://localhost/ajaxTest", false);
    xml.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xml.send("format=json");
    var resp = xml.responseText;
    console.log(resp);
}

And PHP:

<?php
    if (isset($_POST["format"])){
        if($_POST["format"] == "json"){
            echo '
                {
                    "name": "Name",
                    "lastName": "LastName", 
                    "dob" : "dd/mm/yyyy",
                }
                ';
        }
    }else{
        print_r($_POST);
        echo "Error";
        http_response_code(400);
    }


?>

And whenever I execute my JS I get the error part of the PHP code, even having sent the "format=json" data on request. But if I change asynchronous to true, I get a GET error (in chrome's console) of 400 Bad Request, but no echo of the PHP is executed.

I know I have to check the xmlhttprequest status and response code to do asynchronous, I was testing it directly on the console.

I don't know what I'm doing wrong here, the POST data should be sent, and independently of asynchronous or not, right?

Thank you all!

Upvotes: 2

Views: 15829

Answers (1)

Professor Abronsius
Professor Abronsius

Reputation: 33813

looks like the structure of your javascript function is incorrect. You should setup a listener before you send the request. In your code perhaps something like:-

var xml = new XMLHttpRequest();
xml.onreadystatechange = function() {
    if( xml.readyState==4 && xml.status==200 ){
        console.log( xml.responseText );
    }
};

xml.open("POST", "http://localhost/ajaxTest", false);
xml.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xml.send("format=json");

Upvotes: 4

Related Questions