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
});
});
});