Page 1 of 1

How to echo JSON sent using javascript in

Posted: Sun May 14, 2017 3:30 am
by gautamz07
Hey guys , i have the following update.js file:

Code: Select all

var xhr = new XMLHttpRequest();
		xhr.open('POST' , 'updateuserinfo.php');
		xhr.setRequestHeader('Content-Type' , 'application/json');
		xhr.onload = function() {
			if (xhr.status === 200) {
				console.log('done !');
			}
		}

		let data = {
			name : 'John',
			profession : 'Accountent'
		}

		xhr.send(JSON.stringify(data));

		return false;
	});
and i am sending data to updateuserinfo.php, basically what i want to do is , send the data and then echo the data i have sent in the PHP file. But as of now what is happening is , as soon as i load my index.php file, i get thee following error:

Code: Select all

Notice: Undefined index: data in C:\xampp\htdocs\AjaxUser\updateuserinfo.php on line 3
My updateuserinfo.php file , looks like so:

Code: Select all

<?php 

	$data = $_POST['data'];
	$newUserInfo = json_decode($data, true);
	echo $newUserInfo;

?>
what am i doing wrong here ?

Thank you.
Gautam.

Re: How to echo JSON sent using javascript in

Posted: Sun May 14, 2017 5:05 am
by requinix
You're sending raw data to your script. PHP will not try to interpret that data so you can't use $_POST.

Read the data yourself manually:

Code: Select all

file_get_contents("php://input")