Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data -- FireBug reports this error. Any solution? [duplicate]

Tags:

json

jquery

php

I have used Laravel Response::json to generate a JSON response.

return Response::json(array('subjects' => $subjects, 'year' => $year, 'sem' => $sem));

When I run the request, I get a valid JSON (tested in JSONLint) as a response.

But the following jQuery method fails: $.parseJSON(data)

I get the following error in FireBug:

SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data

The Response I recieve:

{
    "subjects": [
        {
            "id": 1,
            "name": "Control Systems",
            "semester": 1,
            "year": 3,
            "branch_id": 4
        },
        {
            "id": 2,
            "name": "Analog Communications",
            "semester": 1,
            "year": 3,
            "branch_id": 4
        },
        {
            "id": 3,
            "name": "Linear IC Applications",
            "semester": 1,
            "year": 3,
            "branch_id": 4
        },
        {
            "id": 4,
            "name": "Antennas & Wave Propagation",
            "semester": 1,
            "year": 3,
            "branch_id": 4
        }
    ],
    "year": 3,
    "sem": 2
}

And the code where I'm trying to parse it:

$(document).ready(function() {
    $('#branchAndSubjects').click(function() {
        $.post('/findBranchAndSubjects', {
            roll: roll,
            _token: "{{csrf_token()}}"
        }, function(data) {
            var subjects = $.parseJSON(data);
        });
    });
});
like image 755
Faizuddin Mohammed Avatar asked Apr 20 '15 07:04

Faizuddin Mohammed


1 Answers

If you're doing the $.parseJSON(data) in an ajax success handler Since you're doing the $.parseJSON(data) in an ajax success handler, the problem is almost certainly that jQuery has already parsed it for you. jQuery will look at the Content-Type of the response and, if it's application/json, it will parse it, and provide the parsed result to your success handler. The first thing that will happen if you pass that into $.parseJSON will be that it will get converted back to a string ("[object Object]", in your case), which $.parseJSON will then fail to parse.

Just use data as-is, it's already an object, thanks to the automatic parsing:

$(document).ready(function() {
    $('#branchAndSubjects').click(function() {
        $.post('/findBranchAndSubjects', {
            roll: roll,
            _token: "{{csrf_token()}}"
        }, function(data) {
            console.log(data.year);             // 3
            console.log(data.subjects.length);  // 4
            console.log(data.subjects[0].name); // Control Systems
        });
    });
});
like image 154
T.J. Crowder Avatar answered Oct 18 '22 21:10

T.J. Crowder