SyntaxError: JSON.parse: unexpected character in row 1 of column 2 of JSON data - FireBug reports this error. Any solution?

I 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 valid JSON (verified in JSONLint) as the response.

But the following jQuery method does not work: $.parseJSON(data)

The following error appears in FireBug:

SyntaxError: JSON.parse: unexpected character in row 1 of column 2 of JSON data

The answer I get is:

 { "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 try to parse it:

 $(document).ready(function() { $('#branchAndSubjects').click(function() { $.post('/findBranchAndSubjects', { roll: roll, _token: "{{csrf_token()}}" }, function(data) { var subjects = $.parseJSON(data); }); }); }); 
+8
json jquery php
source share
1 answer

If you execute $.parseJSON(data) in ajax success handler . Since you are executing $.parseJSON(data) in the ajax success handler, the problem almost certainly is that jQuery has already parsed it for you. jQuery will look at the Content-Type response and, if it is application/json , it will parse it and provide the processed result to your success handler. The first thing that happens if you pass this value to $.parseJSON is that it will be converted back to a string ( "[object Object]" in your case) that $.parseJSON will not be able to $.parseJSON .

Just use data as-is, this is an object, thanks to 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 }); }); }); 
+19
source share

All Articles