0

I'm trying to send an object to my server that has keys which contains blanks. For some reason that I don't understand the blanks get converted to underscores at the server. How can I prevent this?

var myObject    = {};
myObject['x x'] = 'asdf';

$.post(someUrl, myObject, function (data) {
    ...
}, 'json');

In my PHP code $_POST is set to this array:

$_POST = [
    'x_x' => 'asdf'
]

Why is that and how do I deal with it? Are there any other characters that get converted this way?

robsch
  • 9,358
  • 9
  • 63
  • 104
  • `var myObject = { 'x x' : 'asdf'}` ? – Hendra Nucleo Aug 16 '16 at 16:26
  • 3
    Possible duplicate of [Get PHP to stop replacing '.' characters in $\_GET or $\_POST arrays?](http://stackoverflow.com/questions/68651/get-php-to-stop-replacing-characters-in-get-or-post-arrays) – Andreas Aug 16 '16 at 16:27
  • The duplicate is about dots but PHP does also change a bunch of other characters, such as space, because of the same reason. – Andreas Aug 16 '16 at 16:29

1 Answers1

0

The workaround/solution that works for me is this, which is an answer to the question that Andreas has provided. In short: PHP converts some characters into underscores (doc comment at php.net). It's not caused by jQuery!

So I wrap my arguments in JS into another object:

var myObject    = {
    arguments: {}
};
myObject.arguments['x x'] = 'asdf';

$.post(someUrl, myObject, function (data) {
    ...
}, 'json');

Now I get this structure in PHP that has the unmodified keys:

$_POST = [
    'arguments' => [
        'x x' => 'asdf'
    ]
]

And I can access it with $_POST['arguments'].

Community
  • 1
  • 1
robsch
  • 9,358
  • 9
  • 63
  • 104