Honzys Honzys - 12 days ago 7
PHP Question

Using square right bracket in php key

I am trying to post a dictionary using ajax. But I have run into some problems with json and "]" character.

Here's example of my code (javascript):

var dict = {"id":"patient","where":{"name[~]":"J"}};
$.post("./ajax.php",{data:dict},function(data){
});


And ajax.php (this file just deals with the json encoded data in $_POST array):

$where = $_POST["data"]["where"];


Basically i am trying to send json format message to php, and there I want to process with the data.

I tried whole bunch of combination with json_encode and decode on php side, also JSON.stringify() on javascript side, tried to use escape characters with the right bracket.

But when I dump $_POST["data]["where] there's value "J" with key "name[~" and not "name[~]". Right bracket disappears from the key.

Anyone having any advice, please?
Thanks for help, I've been struggling with this for hours...

//EDIT: I've figured out, that everything i place after "]" disappears from the key. So the key transforms from "name[~]asdf" -> "name[~"...

Answer

Another solution that worked for me:

JS

$.ajax({
        url: 'recAjax.php',
        method: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(dict)
    });

PHP

var_dump(json_decode(file_get_contents('php://input'), true));

json_decode, php://input

Comments