0

My PHP script is having a problem decoding the JSON that I'm sending to it via AJAX.

The jQuery:

$.ajax({
    url : 'admin/modifyPermissions',
    type : 'post',
    data : {
        'JSON' : JSON
    },
    success : function(msg){
        if(msg == '1') {
            alert('Permissions saved successfully');
        } else {
            alert(msg);
        }
    }
});

The PHP script:

public function modifyPermissions(){

    if(isset($_POST['JSON']) && !empty($_POST['JSON'])) {
        $json = json_decode($_POST['JSON'],true);
        if($json !== NULL && $json !== FALSE) {

        } elseif($json === NULL){
            die('The string passed is not a valid JSON object and cannot be decoded.' . "\n" . $_POST['JSON']);
        } else {
            die('There was an error with the JSON string');
        }
    } else {
        die('No JSON string was sent!');
    }
}

The JSON that gets passed looks well formed to me:

{"martin":{3,5},"user2":{3,4,5}}

And PHP is returning null. I have PHP 5.2.7 installed on my server, so I can't use json_last_error()

2
  • 5
    Your JSON should be {"martin":[3,5],"user2":[3,4,5]} Note the use of [ and ] for ordered sets over { and }
    – Matt
    Apr 16, 2012 at 14:09
  • 1
    It doesn't matter that the JSON looks well-formed to you, because it's not. When in doubt, use a JSON validator to check: jsonlint.com
    – Matt Ball
    Apr 16, 2012 at 14:10

3 Answers 3

5
{"martin":{3,5},"user2":{3,4,5}}

Not valid JSON. Valid JSON may look like this:

{"martin":[3,5],"user2":[3,4,5]}
1
  • Wow, that's embarrassing. I can't believe I didn't see that. Thank you!
    – xyhhx
    Apr 16, 2012 at 16:58
0

You're not sending valid JSON, thus the error. Look at the comment @Matt added.

So that you won't reproduce the same error, before sending it over to PHP, don't try to make your own JSON string, use what JS offers you. Example:

var obj = { key: val, okey: oval }
objJSON = JSON.stringify(obj)
// objJSON is ALWAYS going to be valid json
0

Your JSON is invalid.

The {} notation denotes key/value pairs, where as you're using it as an array.

Your JSON should be,

{"martin":[3,5],"user2":[3,4,5]}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.