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.
{}overnew Object(), and you don't have to initialize your properties before setting them to your real value. Replace your entire first example with this:json = { pattern: { '@id': id '@num': pn, 'cprop': { '$': bp.find('input[name="submit"]').val() || '' } } }. And since you're using jQuery, just useurl: patterninstead.json_last_error()(us2.php.net/function.json_last_error)? It may tell you outright what the problem is, or at least give guidance.