SitePoint Sponsor

User Tag List

Results 1 to 8 of 8

Thread: Jquery and Json

  1. #1
    SitePoint Enthusiast
    Join Date
    Jul 2004
    Location
    France
    Posts
    94
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Unhappy Jquery and Json

    Hi everyone, i got a problem with a json response from an ajax request.

    I have the following code :
    Code:
    $.get(  "ajax_sous_famille.php",
            {"id": $(this).attr("value")},
            function(data)
            {
                // whatever !!!
            },
            "json"
    );
    And the called page (ajax_sous_famille.php) is giving me this result :
    Code:
    [{"id":"25","nom":"Pouf slim"},{"id":"26","nom":"Pouf g\u00e9ant"},{"id":"27","nom":"Pouf XXL"},{"id":"28","nom":"Pouf Int\u00e9rieur"}]
    The info in the resulting string is correct, but here you can see the [ ] at the start and end of the line.
    It seems not to be a correct Json string and then it crashes my script !

    I have another request like this which gives me the good format of resulting data (without the [ ]) and which works perfectly when i decode the Json string to display it.

    The difference between the 2 requests is that the one which works returns only 1 array of values like
    Code:
    array(
       "key1" => "value1",
       "key2" => "value2",
       "key3" => "value3"
    );
    and the second one which doesn't work returns something like
    Code:
    array(
       record1(array(
          "key1" => "value1",
          "key2" => "value2",
          "key3" => "value3"
          );
       ),
       record2(array(
          "key1" => "value1",
          "key2" => "value2",
          "key3" => "value3"
          );
       ),
       record3(array(
          "key1" => "value1",
          "key2" => "value2",
          "key3" => "value3"
          );
       )
    );
    Actually, all the records are coming from a database and in the case it doesn't work, i wanna get several results from this database.

    Does anyone have an idea of how i can make my Json answer correctly formated, or how i can achieve this if Json format is not the answer ?
    Thanx

  2. #2
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,197
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    You can trying using jQuery.parseJSON(), the API seems to be down but see the example below for a quick reference.

    Code JavaScript:
    var obj = jQuery.parseJSON('{"name":"John"}');
    alert( obj.name === "John" );

  3. #3
    SitePoint Enthusiast
    Join Date
    Jul 2004
    Location
    France
    Posts
    94
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I agree but it works well for 1 record.
    Actually, i have this type of string format using json_encode() php function on an array with info from mysql, like this :
    Code:
    $id = $_GET['id'];
    $retour = array();
    
    if($id)
    {
        $db = new DB();
        $db->query("SELECT * FROM familles WHERE idParent=".$id." ORDER BY ordre");
        $db->close();
        while($r = $db->next_record())
        {
            $temp['id'] = $r['id'];
            $temp['nom'] = $r['nom'];
            $retour[] = $temp;
        }
    }
    else
    {
        $retour[0]['id'] = 'void';
    }
    
    echo(json_encode($retour));
    , but i have those [ ] that seem to screw it all :

    [{"id":"25","nom":"Pouf slim"},{"id":"26","nom":"Pouf g\u00e9ant"},{"id":"27","nom":"Pouf XXL"},{"id":"28","nom":"Pouf Int\u00e9rieur"}]

    With only {"id":"25","nom":"Pouf slim"} (for instance), obj.id gives 25, but i wanna have several lines of DB records and not only 1.
    How can i achieve this plz ?

  4. #4
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,197
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    Because your appending array values without setting an array key i believe that's what is causing it. If you use the following does it work?

    PHP Code:
    $id $_GET['id'];
    $retour = array('records' => array());

    if(
    $id)
    {
        
    $db = new DB();
        
    $db->query("SELECT * FROM familles WHERE idParent=".$id." ORDER BY ordre");
        
    $db->close();
        while(
    $r $db->next_record())
        {
            
    $temp['id'] = $r['id'];
            
    $temp['nom'] = $r['nom'];
            
    $retour['records'] = $temp;
        }
    }
    else
    {
        
    $retour[0]['id'] = 'void';
    }

    echo 
    json_encode($retour); 

  5. #5
    SitePoint Enthusiast
    Join Date
    Jul 2004
    Location
    France
    Posts
    94
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    So doing what you say, i will have (assuming there are 4 records in my table) :
    1st loop ==>
    $retour['records']['id'] = "25";
    $retour['records']['nom'] = "Pouf slim";
    2nd loop ==>
    $retour['records']['id'] = "26";
    $retour['records']['nom'] = "Pouf g\u00e9ant";
    3rd loop ==>
    $retour['records']['id'] = "27";
    $retour['records']['nom'] = "Pouf XXL";
    4th loop ==>
    $retour['records']['id'] = "28";
    $retour['records']['nom'] = "Pouf Int\u00e9rieur";
    And in the end, i'll only have 1 record in my variable with id=28 and nom=Pouf Int\u00e9rieur inside.

    So i tried something else doing this :

    Code:
    $id = $_GET['id'];
    $retour = array();
    
    if($id)
    {
        $db = new DB();
        $db->query("SELECT * FROM familles WHERE idParent=".$id." ORDER BY ordre");
        $db->close();
        $i = 0;
        while($r = $db->next_record())
        {
            $temp = array();
            $temp['id'] = $r['id'];
            $temp['nom'] = $r['nom'];
            $retour['record'.$i] = $temp;
            $i++;
        }
    }
    else
    {
        $retour['record0']['id'] = 'void';
    }
    
    echo(json_encode($retour));
    Then i obtain :

    {"record0":{"id":"25","nom":"Pouf slim"},"record1":{"id":"26","nom":"Pouf g\u00e9ant"},"record2":{"id":"27","nom":"Pouf XXL"},"record3":{"id":"28","nom":"Pouf Int\u00e9rieur"}}

    So i've managed to achieve what i wanted but there's one remaining problem : when i wanna browse my record table, doing for(i = 0 ; i < data.length ; i++), where data is the return of "$retour", data.length is undefined !
    Doing it by hand setting for(i = 0 ; i < 4 ; i++), it works perfectly.
    I've searched for info on JS objects but it seems it's the right syntax.
    object.length !!!
    Have you got an idea ?

    PS : BTW thanx a lot for your help

  6. #6
    SitePoint Enthusiast
    Join Date
    Jul 2004
    Location
    France
    Posts
    94
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Just to test, i tried this (this is the format of my data) :
    Code:
    var test = new Object();
    test['record0'] = new Object();
    test['record0']['id'] = "1";
    test['record0']['nom'] = "test1";
    test['record1'] = new Object();
    test['record1']['id'] = "2";
    test['record1']['nom'] = "test2";
    test['record2'] = new Object();
    test['record2']['id'] = "3";
    test['record2']['nom'] = "test3";
    
    alert(test.length);
    and it's undefined !

  7. #7
    SitePoint Enthusiast
    Join Date
    Jul 2004
    Location
    France
    Posts
    94
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    OK here's the trick (for the ones who are interested) :
    The "length" propriety doesn't exist for objects (associative arrays) !
    You have to "simulate" it by doing a counting loop like this :
    Code:
    var n=0;
    for(x in data)
    {
        n++;
    }
    'n' is your data.length !
    I hope it works on all platforms and all browsers (i only tested on WinXP/FF3.6) !!!

    Thx for your support SgtLegend.

  8. #8
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,197
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    No problem, glad you got it sorted.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •