treehouse : what would you like to learn today?
Web Design Web Development iOS Development

[Solved] JQuery and JSON help

  • I hope someone can help me, I have an AJAX call which loads some data from a database and returns it as JSON. The code I use is:


    $.ajax({
    type: \"POST\",
    url: \"ajaxhandler.php\",
    data: \"action=svgjson\",
    datatype: \"json\",
    success: function(json){
    $('#searchResults').html(json);
    }
    });


    This works fine and returns the JSON and dumps the lot in the browser. However, I am having trouble parsing the file and getting the details I want from it. The file is structured as so:

    {
    \"floorplan\":[
    {
    \"id\":\"1\",
    \"room\":\"9000\",
    \"use\":\"Gallery\",
    \"category\":\"Gallery\",
    \"colour\":\"#FFFF22\"
    },
    {
    \"id\":\"3\",
    \"room\":\"9001\",
    \"use\":\"Store Room\",
    \"category\":\"Utility\",
    \"colour\":\"#000000\"
    }]}


    Say I want to get the colour for each floorplan item. How do I go about doing this? I was thinking something like:
    $('#searchResults').html(json.floorplan.colour);


    But it just returns the error
    TypeError: Result of expression 'json.floorplan' [undefined] is not an object.


    Any help is much appreciated!



    EDIT: Never mind, fixed it myself. Apparently it was returning a string not an object so I had to use the eval() function to convert the string to an object. Now works perfectly!