I have made an AJAX function, and it actually works, but I can't get the variable with PHP. This is my code:
// Validate signup
function validateSignup(){
// Get values
var username = document.getElementById("pm_username").value;
var email = document.getElementById("pm_email").value;
var password = document.getElementById("pm_password").value;
// Make new object
var data = {};
// Make array from object
data['data'] = [];
// If values are not empty...
if(username !== "" || email !== "" || password !== ""){
data['data'].push(email, username, password);
// Convert data to JSON string and make new XMLHttpRequest
var json = JSON.stringify(data['data']), xhr = new XMLHttpRequest();
// Page to open
xhr.open("POST", "ajax/signup.php", true);
// Set header to POST
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Send values
xhr.send(json);
console.log(json);
xhr.onload = function(){
console.log(xhr.responseText);
}
}else{ // ...or throw new exception
throw("Some thing was not filled in!");
}
}
It works, but I don't know how I should get the JSON variable in my PHP. This is my PHP code (simple):
<?php
$json = $_POST['json'];
echo $json;
echo "Test";
?>
It works, because the "Test" echo is being displayed in the console. However, I am getting this back:
<br />
<b>Notice</b>: Undefined index: json in <b>G:\usbwebserver\root\pokemonisle\ajax\signup.php</b> on line <b>3</b><br />
Test
That means that the $_POST['JSON'] is not being recognised. I am not using jQuery because I want to learn how XMLHttpRequests work.