Search code examples
javascriptphpxmlhttprequest

Can't pass a parameter to $_POST using the XMLHttpRequest


I'm practicing PHP and the use of the XMLHttpRequest object. I'm trying to make a function that checks whether a username is already taken or not.

This is my javascript function:

function checkUser(username) {
if (username.length < 8) return 2;

request = new XMLHttpRequest();

request.open("POST", "checkUser.php?t=" + Math.random(), true);
request.setRequestHeader('Content-type', 'application/x-www-urlencoded');
params = 'nameToBeChecked=' + username; 

request.onreadystatechange = function() {
    if(request.readyState == 4 && request.status == 200) {
        if(request.responseText == "true") {
            return 1;
        }
        else if (request.responseText == "false") {
            return 0;
        }
        else console.log("ERROR: " + request.responseText);
    }
}
request.send(params);
}

This is my PHP file:

require 'userActions.php';

if(isset($_POST['nameToBeChecked'])) {
    if(fetch_userid($_POST['nameToBeChecked']) == null) echo "true";
    else echo "false";
}
echo !isset($_POST['nameToBeChecked']) ? "Field doesn't exist" : "Field exists" ;

The last line on my PHP file is there for debugging purposes. I discovered that when I send a POST request to my PHP file, the field nameToBeChecked isn't created in the PHP file. I can't find what the problem is online. Can someone help?


Solution

  • Try again after you change this line:

    /* request.setRequestHeader('Content-type', 'application/x-www-urlencoded'); */
    request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    

    as defined here: application/x-www-form-urlencoded from https://developer.mozilla.org/