How to echo JSON sent using javascript in

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
gautamz07
Forum Contributor
Posts: 331
Joined: Wed May 14, 2014 12:18 pm

How to echo JSON sent using javascript in

Post 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.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: How to echo JSON sent using javascript in

Post 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")
Post Reply