How to properly parse Result Array from database with Jquery?

I have codeigniter application which fetches data from database and this data is manipulated by Jquery. Result array from database used to look like this:

 { "result":[
    {"name":"John","surname":"Smith"}] }

And I use to parse it using code below:

$.get("index.php/getResult",{f_name: $('#fn').val()} ,function(data) {
    var list= "";
    $.each(data, function(index, element) {
        if (index > 0) {list;}
        list+= element.name;
    });
    $('#myid').html(list);
},"json");

My result array has changed to the format below, how can I parse it now? Any help is appreciated.

{
"count": 8,
"result":[
{"name":"John","surname":"Smith"}] }

Upvotes: 3

Views: 547

Answers (2)

chsymann
chsymann

Reputation: 1670

As you are using json (what means J ava S cript- O bject- N otation) you can use this object like any ohter JavaScript object. So you can access result[0].name for example. For debugging i recommend to use Firebug Add-On for Firefox or Chrome Webdevelopertool. In both you can write console.log(data) or console.log(result[0].name) for example and view your object in console-tab.

Upvotes: 1

Lee Taylor
Lee Taylor

Reputation: 7984

You don't need to parse anything:

$.get("index.php/getResult",{f_name: $('#fn').val()} ,function(data) 
{
    alert(data.count);

    for(var i=0; i< data.result.length; i++)
    {
        alert(data.result[i].name + " " + data.result[i].surname);
        // etc.
    }
    // etc.

},"json");

Upvotes: 3

Related Questions