JSON and AJAX special Characters and escaping.

Hi,

I am using AJax to send a string to a server side PHP app.

In Javascript, before I make the call to AJax, I call  stringify, see attached code part 1.  Stringify will replace 'some' special chars with uuencode equivalents, see attached image 'after-stringify.png'.

When the PHP code receives this, AJax has made further escapes to special characters, and also removed stringify's escape of the lf.  See attached image 'received-at-php'.

At the very least before I can use json_decode I have to remove the double quotes, see attached code part 2.

This will then give me almost the result I want... see image 'after-json-decode.png'.

But as you can see, because AJax stripped out the '\' for the u000a, i"m left with that in the middle.

What I've done seems very hackish and not correct.

How do I do this correctly, code examples please.

Thanks
Phil




// code part 1 -- javascript

var newMess = new Object();
var toList  = new Object();

toList = "63,64";

newMess["toList"] = toList;
newMess["subject"] = messSubject;
newMess["body"] = messContent;

var newMessToSend = JSON.stringify(newMess);

alert(Params);

// code part 2 -- PHP

$tmp = str_replace("\\", "", $pNewmess);
$newMess = json_decode($tmp);

Open in new window

after-stringify.png
received-at-php.png
after-json-decode.png
BeerFizzAsked:
Who is Participating?
 
hieloCommented:
instead of:
var newMessToSend = JSON.stringify(newMess);

use:
var newMessToSend = encodeURIComponent( JSON.stringify(newMess) );

then on the server instead of:
$tmp = str_replace("\\", "", $pNewmess);


use:
$tmp = stripslashes( $pNewmess );

0
 
BeerFizzAuthor Commented:
Excellent!!  Thanks.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.