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);
});
});
});
If you're doing the Since you're doing the $.parseJSON(data)
in an ajax success handler$.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
});
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With