Skip to content Skip to sidebar Skip to footer

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','wher

Solution 1:

When you provide an object to the jQuery AJAX functions, it URL-encodes it. jQuery is sending the data.where parameter as:

data[where][name[~]]=J

and PHP apparently can't deal with nested brackets like that; it just matches the [ before name with the next ].

Probably jQuery needs to double-encode this property name to protect it, but obviously it doesn't.

The workaround is to encode dict as JSON, and decode it in PHP. JS:

$.post("./ajax.php",{data: JSON.stringify(dict)},function(data){

PHP:

$data = json_decode($_POST['data'], true);$where = $data['where'];var_dump($where);

Solution 2:

I have tried JSON.stringify in junction with json_decode and the result looks fine:

JS

$.ajax({
        url: './ajax.php',
        method: 'post',
        data: "data="+JSON.stringify(dict)
    });

PHP

json_decode($_POST['data'], true);

I think you should have specified the JSON is associative, setting $assoc parameter to true. See this.

You can also send data as a JSON (not string) and then read the raw post data using php://input stream and use json_decode with $assoc set to true on the retrieved data yourself; since it appears that out-of-the-box method compiled into PHP is inefficient.

Solution 3:

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

Post a Comment for "Using Square Right Bracket In Php Key"