jquery, php and ajax - Attempting to alert my JSON created with PHP and AJAX it my page.
hello all,
HTML Code:
- <script type="application/javascript">
- $(document).ready(function() {
- $("#addlivestock").validator();
-
- $.getJSON(
- "get_location.php",
- function(data)
- {
- alert(data.location); //alerts undefined
- /*for (var i = 0; i < data.length; i++) //attempt to loop through JSON and add the results to a select
- {
-
- }*/
- }
- );
-
- });
- </script>
PHP Code:
- <?php
- require_once 'MDB2.php';
-
- $dsn = 'mysqli://***:***@localhost/lsms';
- $options = array(
- 'debug' => 2,
- 'result_buffering' => false,
- );
-
- $mdb2 =& MDB2::factory($dsn, $options);
- if (PEAR::isError($mdb2)) {
- die($mdb2->getMessage());
- }
-
- // Proceed with a query...
- $res =& $mdb2->query('SELECT * FROM location');
-
- // Always check that result is not an error
- if (PEAR::isError($res)) {
- die($res->getMessage());
- }
-
- //Create a location array to store the results pulled from the database.
- $location = $res->fetchAll(MDB2_FETCHMODE_OBJECT);
-
- echo json_encode($location);
-
- $mdb2->disconnect();
- ?>
The php code works as expected and echos out:
[{"id":"3","location":"Chicken Pen 1"},{"id":"4","location":"Chicken Pen 2"},{"id":"5","location":"Chicken Pen 3"},{"id":"6","location":"Chicken Pen 4"}]
alert(data.id); alerts undefined. I'm attempting to make sense of this issue and can't figure out why Its not alerting the locations. I checked the response of get_location.php in firebug and the JSON data is there. Any help is greatly appreciate!
Thanks,
Rich