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:\usbwebserveroot\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.
Your POST
array doesn't contain a field named json.
Try the following:
<?php
var_dump($_POST);
?>
to check which fields you are getting.
To prevent the error you could try:
<?php
if(isset($_POST['json']))
{
$json = $_POST['json'];
echo $json;
}
?>
and similarly to get other variable you could use:
<?php
if(isset($_POST['username']))
{
$username = $_POST['username'];
echo $username;
}
?>
You do not send a post data named 'json', so you can't get it on server side.
Try to stringify your data object like
var json = "json="+JSON.stringify(data['data']);
and get it as
$json = $_POST['json'];
You can check out this link. Send POST data using XMLHttpRequest
A string is generated of the array when you "JSON.stringify(data['data'])" it.
For example the output of this
var name ="abc";
var surname ="xyz";
var data ={};
data['data']=[];
data['data'].push(name, surname);
var json = JSON.stringify(data);
console.log(json);
shall be
{"data":["abc","xyz"]}
The $_POST['json'] should give you what .???
The $_POST['name'] (in a form for example) gives you the value of the field username.