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);
}
?>