3

Let's say I'm trying to send a data to PHP and receive it using pure Javascript.

So when I'm sending a string "login="+1+"&username="+username+"&password="+password; with Ajax It's all ok but what about an Object? in this case, my PHP code always telling username and password are Undefined indexes.

HTML Document :

<body>
<form id="loginform">
    <input type="text" placeholder="username"  id="username" required autocomplete="off"><br>
    <input type="password" placeholder="password" id="password" required><br>
    <input type="submit" id="submit">
</form>

<script>
        document.getElementById("loginform").addEventListener("submit", function(e) {
            e.preventDefault();

            var username = document.getElementById("username").value;
            var password = document.getElementById("password").value;

            var data = {// ---- there is my Object -----
                login: 1,
                username: username,
                password: password
            }

            var xhr = new XMLHttpRequest();
            xhr.open("POST", "process.php", true);

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

            xhr.onload = function() {
                console.log(this.responseText);
            }

            xhr.send(data);
        });
</script>
</body>

PHP Document :

<?php
    if(isset($_POST["login"])) {
        $username = $_POST['username'];
        $password = $_POST['password'];
        echo($username . " , " . $password);
    }
?>

1 Answer 1

2

what about an Object?

send() doesn't expect to be passed a plain object, so it converts it by calling its toString() method, which gives you "[object Object]", which (obviously) isn't URL encoded data.

Not only does PHP not understand it, but the data you want to send isn't included in it in the first place.


If you have an object, you need to convert it into a format that you can decode on the server.

Continuing to use form encoded data is the simplest approach.

var data = {
  login: 1,
  username: "example",
  password: "example"
};

var key_value_pairs = [];

Object.keys(data).forEach(function(key) {
  key_value_pairs.push(
    encodeURIComponent(key) + "=" + encodeURIComponent(data[key])
  );
})

var url_encoded_string = key_value_pairs.join("&");

console.log(url_encoded_string);


You could also send the data using a different format. PHP understands multipart MIME encoding which you can generate with a FormData object.

var form_data = new FormData(document.getElementById("loginform"));
form_data.append("login", "1");
xhr.send(form_data);

If you do this, do not override the Content-Type with:

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

XMLHttpRequest will generate the correct-content type, with the multipart MIME boundary parameter from the FormData object.


You could also encode the data with a different data format, such as JSON:

xhr.setRequestHeader('Content-type', 'application/json');
xhr.send(JSON.stringify(data));

… but, and this is a big but, PHP does not know how to decode JSON formatted requests and will not automatically populate $_POST.

You would need to change the PHP to read the data:

$json = file_get_contents('php://input')
$data = json_decode($json));
var_dump($data);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.