Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    FDI
    FDI is offline
    New to the CF scene
    Join Date
    Oct 2010
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    can't access JSon via JQuery

    Hello
    I'm trying to display data from mysql database using getJSON

    this is the code
    JQuery Code
    Code:
    //get data from database
    	$.getJSON('getCategories.php', parseCat);
    
    // display data
    function parseCat(data)
    {
    	console.log(data.fname);
        $('#info').html(data.fname +', ');
    }
    Php Code
    Code:
    <?php
    
    $dsn = "mysql:host=localhost;dbname=client";
    $username = "root";
    $password = "";
    
    try {
        $pdo = new PDO($dsn, $username, $password);
    }
    catch(PDOException $e) {
        die("Could not connect to the database\n");
    }
    $stmt = $pdo->prepare("SELECT fname,lname FROM client");
    $stmt->execute();
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode($rows);
    
    ?>
    this return undefined
    Code:
      $('#info').html(data.fname +', ');
    but in firebug I can see the result
    Code:
    [{"fname":"test","lname":"test"},{"fname":"fadi","lname":"yousef"},{"fname":"fadi","lname":"yousef"}]
    but can't access them

    any help please
    thanks in advanced

  • #2
    Regular Coder
    Join Date
    May 2009
    Posts
    425
    Thanks
    3
    Thanked 62 Times in 61 Posts
    I'm not familiar with jQuery but it looks to me like you aren't parsing the returned data string. Try something like this:

    PHP Code:
    //get data from database
        
    $.getJSON('getCategories.php'parseCat);

    // display data
    function parseCat(data)
    {
        var 
    dataObj json.parse(data);
        
    console.log(dataObj);
        $(
    '#info').html(dataObj['fname'] +', ');

    Or does jQuery automatically parse it for you with the getJSON function? By looking at your console log though it looks like it doesn't.


  •  

    Tags for this Thread

    Posting Permissions

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