Sending special characters in Ajax POST and JSON

Victor Ferreira picture Victor Ferreira · Aug 23, 2014 · Viewed 10.3k times · Source

@SOLVED

As explained by James M. Lay, I should change my content-type from application/x-www-form-urlencoded to application/json

it implied in an error because it seems that only UrlEnconded types generates POST arrays in server side (at least in PHP). So I had to change the way I receive/deal with the request in my server script

$json = file_get_contents('php://input'); //yes. php://input

if($json) $params = json_decode($json,true);
else $params = $_POST;

I also had to make a few changes in the Javascript code to check the content-type and generate different strings. If it's JSON I just use JSON.stringify

//string to use in the 'send' method
this.getParametersString = function(){
        if(this.contentType == 'application/json'){
            return JSON.stringify(this.parameters);
        }else{}
}

I got a question

I`m building a function that receive parameters to write a list of parameters and send it by POST

The problem is that we can't send special characters, such is +

So I tried to use the function encodeURIComponent to encode them to a URI friendly string.

There comes another problem: if the parameter received is an object, I am loop through the attributes, checking if it is another object or a string, if it is an object, loop again, otherwise encode it.

But it is returning an object of encoded strings. I have to make the object become a string to send it, and for that purpose I use JSON.stringify. It decodes the encoded string. So %2B becomes + again and It is not sent to the server via POST.

on the other hand If I use stringify first and the encodeURIComponent it generates signs like " and { } that shouldn't be encoded and the string is not a well written JSON

How do you that? Is that a way without using jQuery? Do I have to build my own stringify function?!

Answer

King Loui picture King Loui · Aug 23, 2014

im using the following and i have no issues

encodeURIComponent(JSON.stringify(object_to_be_serialised))