JSON and AJAX special Characters and escaping.


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.


// 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);


// code part 2 -- PHP

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

Open in new window

Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

instead of:
var newMessToSend = JSON.stringify(newMess);

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

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

$tmp = stripslashes( $pNewmess );


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
BeerFizzAuthor Commented:
Excellent!!  Thanks.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.