Passing json through querystring?

badgettz
badgettz used Ask the Experts™
on
I've been having problems with trying to pass a serialized json object through a query string. It gets the destination fine, but for whatever reason I can't decode it.

Decoding: {"x": 343} - Syntax error, malformed JSON
Decoding: {"x": 343} - No errors
Decoding: {"Organization": "PHP Documentation Team"} - No errors

The first decode is using the "get" method to grab the data, the second decode is using a string that I created with the same data. Anyone know why this would be happening?

Data being passed: "?data={"x"%3A 343}"
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
leakim971Multitechnician
Top Expert 2014

Commented:
Use : http://www.w3schools.com/jsref/jsref_encodeURI.asp
var param = "?data=" + encodeURI( jsonString );

Open in new window

leakim971Multitechnician
Top Expert 2014

Commented:
Or : "?data=%7B%22x%22%3A%20343%7D"

you need to escape all this characters : { " : }

Author

Commented:
the URL is being encoded just fine...hence I'm getting the data just fine, php is just not reading it correctly. The reason why the { } aren't encoded is because firefox changes them to their char when you go to the url. Anymore suggestions?
leakim971Multitechnician
Top Expert 2014

Commented:
>Anymore suggestions?

Please post your code : script on the client side doing the encoding

Author

Commented:
?data=" + encodeURI(JSON.stringify(this.json))

Author

Commented:
why would both variables be resulting in the same string but have two different results?
leakim971Multitechnician
Top Expert 2014

Commented:
How do you decode on the server side ?

By this way :

        $json = str_replace("\\", "", $_GET['data'] );
        $json =  json_decode($json);

?
Multitechnician
Top Expert 2014
Commented:
Test page :

(save as : testjson.php)
<html>
<head>
<script language="javascript">
    var json = {"x": 343};
    function sub() {
        jsonStr = encodeURI(JSON.stringify(this.json));
        window.location = "testjson.php?data=" + jsonStr;
    }
</script>
</head>
<body>
<input type="button" onclick="sub();" value="click me !" />
<?php
    if(isset($_GET['data'])) {
        $json = str_replace("\\", "", $_GET['data'] );
        $json =  json_decode($json);
        $x = $json->x; 
        echo "<p> X = " . $x . "</p>";
    }
?>
</body>
</html>

Open in new window

Author

Commented:
The test works, although this did not solve my problem. I'm a little confused because I have pretty much the exact same code.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial