Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decode JSON with jQuery / AJAX

I'm trying to decode a JSON with jQuery. Here's what I get (for instance a class, here with one student):

"{"Students":[{"Name":John,"Grade":17,}],"TotalClass":17,"TotalCount":1,}"

here's what I do:

$j.ajax({
    type: 'POST',
    url: 'class.aspx/getClass',
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function (msg) {
        $j.each(msg, function (index, element) {
            alert(element.TotalClass);
        });
    },
});

It keeps saying undefined in the alert (but I recieve the right JSON). Any idea what I'm doing wrong?

like image 263
blop Avatar asked Jun 13 '12 15:06

blop


2 Answers

{"Students":[{"Name":John,"Grade":17,}],"TotalClass":17,"TotalCount":1,}

is not valid JSON !

Assuming you have a valid JSON like this

{
    "Students": [
        {
            "Name": "John",
            "Grade": "17"
        }
    ],
    "TotalClass": " 17",
    "TotalCount": "1"
}

You can access the values like this

alert("TotalClass : "+msg.TotalClass);
//loop thru students
$.each(msg.Students,function(index,item){
   alert(item.Name+ " - "+item.Grade)
}); 

Working sample : http://jsfiddle.net/ncbLF/5/

Use jsonlint to validate JSON

So your code can be simplified to

$.getJSON("class.aspx/getClass",function(msg){

    alert("TotalClass : "+msg.TotalClass);
    $.each(msg.Students,function(index,item){
        alert(item.Name+ " - "+item.Grade)
    });
});
like image 136
Shyju Avatar answered Sep 21 '22 05:09

Shyju


contentType is the type of the data sent to the server, not from. Remove that.

The JSON you included in the question. Is that the exact JSON the server returns? Because if it is, you don't need the $.each. You have an object, you should only need $.each to loop though an array of objects.

So, just try alert(msg.TotalClass).

Also, that JSON is invalid. You have an extra , after TotalCount, and after Grade. Also, John should be in double quotes.

like image 39
Rocket Hazmat Avatar answered Sep 22 '22 05:09

Rocket Hazmat