views:

62

answers:

2

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.

+2  A: 

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'
WishCow
Thanks, I think you've pretty much answered my question and clarified a hell of a lot for me. Can you just throw in an example of a JSON encoding and how you'd encode something in Javascript and Decode it in PHP? I'll give check your answer as the right one if you can help me with that please.
dscher
Included an example.
WishCow
Thanks, you're great.
dscher
A: 

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.

Tgr