Boardy
Boardy

Reputation: 36205

Getting JSON data from Javascript

I am currently working on a php/javascript project which retrieves information from a database and json encodes the data. It is supposed to show the values from the database inside a combo box on the web page.

In the PHP script that encodes the mysql data I have the following code:

$query = "SELECT pla_platformName as `platform` FROM platforms";

    $result = mysql_query($query);

    if ($result)
    {       
        while ($myrow = mysql_fetch_array($result))
        {
            $output[] = $myrow;                     
        }

        print json_encode($output);
        die();
    }

In the javascript code I have the following:

<script>
        $(document).ready(function()
        {
            getPlatforms();
            function getPlatforms()
            {
                $.post("phpHandler/get-platforms.php", function(json)
                    {
                        alert(json);    
                        alert(json.platform);
                    }
                );
            }
        });
    </script>

I have alert(json); which shows the entire json data which looks like the following:

[{"0":"hello","platform":"hello"},{"0":"android","platform":"world"}]

The next alert(json.platform) I am expecting it to show either hello or world or both but on this line it keeps on saying undefined. Why isn't this working and how do I get a specific platform, i.e. either hello, or world.

Thanks for any help you can provide.

Upvotes: 0

Views: 2006

Answers (2)

Doug Owings
Doug Owings

Reputation: 4448

You need to first convert your JSON string into an object

var data = $.parseJSON(json);

In this case, the object returned is an array. Try

alert(data[0].platform);

You can skip the first step if you set the dataType option to json in your ajax call.

$.post("phpHandler/get-platforms.php", function(data) {
     alert(data[0].platform);
  }, 
  'json'
 );

See jQuery.post() documentation

Upvotes: 4

Gaute L&#248;ken
Gaute L&#248;ken

Reputation: 7892

Your platform member is defined on each item, you'll have to specify which array item you want the platform for. This should do the trick:

alert(json[0].platform);

I'm assuming that your json parameter actually holds a javascript object, and not simply a string. If it is a string, you should define contentType 'application/json' on your php page. (I'm not sure how you do that in php since I do .NET for server side myself.)

To test it quickly however, you can do a $.parseJSON(json) to get the object.

Upvotes: 4

Related Questions