0

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.

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

4

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.

1 Comment

Ohh.. somebody else posted while I was typing that out.. :) hope it gets you where you're going. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.