I can't for the life of me figure out what I'm doing wrong. It seems like it should be simple because I can't find anyone else with this issue but I can't figure out to send basic data via javascript(jQuery) to PHP and decode it. For the sake of simplicity, this is what I have:
JAVASCRIPT
var json_data = { "name" : "john doe" };
$.ajax({
type: "POST",
url: "../bin/process.php",
dataType: "json",
data: json_data
});
and my PHP FILE
$arr = json_decode("json_data", true);
$fp = fopen('data.txt', "w");
fwrite($fp, $arr['name']);
fclose($fp);
The file I'm writing ends up with nothing in it. If I do an:
fwrite($fp, 'test');
I get a file with the word test in it but no matter what I do I don't get the json data I sent.
Can someone please share a thorough example of A to Z. Thanks for any help.
The ajax request that you make with jQuery will send the parameter 'name', with the value 'john doe', and not the whole object. If you want to send the whole object, you have to pass it like this:
data: { parameters: json_data }
On the PHP side, you can get the variables from the $_POST superglobal. Using your example, you would use:
$name = $_POST['name'];
Or, if you send the whole object, using my example:
$params = $_POST['parameters'];
There is no need to use json_decode(), since the parameters you pull out from the $_POST array will be native PHP variables already.
You only need to use it, if you have a json string, which you want to turn into a PHP variable, which is not the case here, since jQuery will "transform" the javascript object, to a query string in the background.
It is a rare case that you need to send data from javascript in a JSON form, but if you want to do that you need something like:
// JS
var person = "{ name: 'John Doe' }"; // notice the double quotes here, this is a string, and not an object
$.ajax({
type: "POST",
url: "../bin/process.php",
dataType: "json",
data: { json: person }
});
// PHP
$json = $_POST['json']; // $json is a string
$person = json_decode($json); // $person is an array with a key 'name'
jQuery cannot encode data to JSON, only decode it (the poorly named dataType
parameter actually refers to the type of the reponse). Use json2.js for encoding.