KenLit
KenLit

Reputation: 33

JSON encode in Javascript and decode in PHP

I create an object in Javascript to pass as the argument to a PHP script.

var pattern = new Object();
pattern['@id'] = '';
pattern['@num'] = '';
pattern.cprop = new Object();
//pattern.aprop = new Object();
pattern['@id'] = id;
pattern['@num'] = pn;
pattern.cprop.$ = pb.find('input[name="subject"]').val() || '';
var json = {'pattern': pattern};

My Ajax call is

url: clr_url_base+'storepat.php?data='+encodeURIComponent($.toJSON(json))

In my PHP script, I use

$pat = json_decode(str_replace ('\"','"', $data), true);
$prep = $pat["pattern"]["@id"];
$sense = $pat["pattern"]["@num"];
$cprop = $pat["pattern"]["cprop"]["$"];
//$aprop = $pat["pattern"]["aprop"]["$"];

This works, but when I add the aprop value, it no longer works.All values are strings. Any suggestions as to what's going wrong.

Here are the two JSON strings:

{\"pattern\":{\"@id\":\"against\",\"@num\":\"1(1)\",\"cprop\":{\"$\":\"a person or thing (often abstract) opposed\"}}}
{\"pattern\":{\"@id\":\"against\",\"@num\":\"1(1)\",\"cprop\":{\"$\":\"a person or thing (often abstract) opposed\"},\"aprop\":{\"$\":\"verbs (to which \'against\' introduces idea of opposition); nouns denoting conflict\"}}}

The first has only has the value for cprop, while the second adds the value for aprop. Note that aprop has single-quotes. It is this kind of data that seems to beg for encoding in the Javascript and decoding in the PHP. The second bombs. I have some 20 fields from a form, so it would get quite complex to create the JSON by hand, rather than as fields in pattern. When the second bombs, the value of $pat is NULL.

Upvotes: 0

Views: 988

Answers (2)

Mike Brant
Mike Brant

Reputation: 71384

I would strongly suggest POSTing the data via jQuery rather than passing in query string. Why? Because then you don't have to worry about URL encoding and such.

This may look like this in javascript/jQuery. Obviously the concept is basically the same for any sort of AJAX sending mechanism.

$.ajax({
    type: 'POST',
    url: clr_url_base+'storepat.php?',
    contentType: 'application/json',
    dataType: 'json', // if you expect JSON in return
    data: json,  // your JSON string here
    success: // your success handler
    error: // your error handler
});

On the PHP-side, since you are not dealing with form-encoded data, you would need to read PHP's raw input. Luckily this is very simple and converting the POST data into a PHP object/array is very trivial. It is as simple as this:

$json = file_get_contents('php://input');
$variable = json_decode($json);

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324640

You have a number of problems, but number one is that you have Magic Quotes enabled. That's why you have all those backslashes. Your crude attempt to "fix" it with str_replace is a bad idea, because there are other things besides " that gets escaped by Magic Quotes. You should find the setting in your php.ini file, and disable it. The same goes for "register globals", a very unsafe feature to be using. Reference $_GET['data'] instead.

With that out of the way, the next thing I would suggest is using POST instead of GET. This means you don't have to mess around with escaping data, as that always comes with the risk of screwing it up.

You should be able to implement these changes without too much trouble.

Upvotes: 0

Related Questions