1

I'm doing an Ajax call to my server and need to send an array. I'm encoding the array using JSON. That results in this data sent to the server using a POST request:

selection=%5B%221%22%5D

On the server, I have this code:

echo urldecode($_REQUEST['selection']);

This results in:

[\"1\"]

Note that there are no backslashes in the request. I checked that with Firefox's dev tools.

Where were the backslashes added? Am I doing something wrong here? I can't decode the string like this.

This is the client-side code:

$.ajax({
    type: "POST",
    url: "<my-uri>/rule/add.php",
    data: {
        selection: JSON.stringify(["1"]) // in reality this is a variable array
    }
}).done(function(data){
    alert(data);
});
  • backslashes are used to escape the double quotes. A simple replace would probably work for you. – Th0rndike Jun 03 '13 at 13:28
  • @Th0rndike yeah, I know, but I can't see where they're added. It might indicate a problem in the code. Does it, or is this normal behaviour? –  Jun 03 '13 at 13:28
  • Why not send it as JSON rather than FOTM data which you need to manually deserialize? – Phill Jun 03 '13 at 13:28
  • @Phill I try to send is as JSON, I'm using `JSON.stringify();` - or do you mean something else? –  Jun 03 '13 at 13:30
  • @Quentin yes, sorry, I didn't find that. –  Jun 03 '13 at 13:31
  • You're sending FORM data with a single key with the serialized JSON. Just do `data: JSON.stringify(["1"])` and deserialize the body. – Phill Jun 03 '13 at 13:32

1 Answers1

0

This happens because your server is configured to add slashes to quotes.

If you wish to avoid this go to your php.ini and set magic_quotes_gpc to 0.

Goran Lepur
  • 594
  • 1
  • 4
  • 15