Ampersand in JSON/PHP in POST

escaping, jquery, json, php, post

Solution

The answer is simple: Use an object for `data` instead of a string.

E.g. change your function like this:

return {data: $.toJSON(this.data)};

This will work in any case, no matter if you are using POST or GET.

Problem

I'm having a text field which is send via JSON and jQuery (wrapped with `.toJSON` function) to my server via AJAX and POST request. On PHP side I'm doing `json_decode` . Everything works but if I put ampersand (&) inside it splits up the POST parameter so its incomplete on PHP side (at least what `var_dump($_POST)` is writing out). Shouldn't the toJSON and json_decode do all the job (escaping)? I tried `encodeURIComponent`, `& to &`, `& to \u0026` and it's not working. What I'm doing wrong? AJAX call ``` function execute() { this.setupUrl(); return $.ajax({ type: this.requestMethod, data: this.getDataParams(), url: this.url }); } function getDataParams() { if(this.data != undefined) { if(this.requestMethod == 'POST' || this.requestMethod == 'PUT') { return "data=" + $.toJSON(this.data); } else if(this.requestMethod == 'GET') { return this.data; } } else { return null; } } ```

Original source