0

The array values return as 'undefined' when printed, even though by using print_r($items) I can see that the array is not empty. What could be the issue here?

MySQL:

Table called 'nights' with columns called 'name', 'price', 'day', 'queue jump', 'closing' and 'doors'. They are all populated.

eventinfo.php:

<?php

header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');

include('functions.php');
connect();

$night = $_POST['club'];
// this echos fine
$night = mysql_real_escape_string($night);

$query = "SELECT * FROM nights WHERE name = '$night'";

    $result = mysql_query($query);
    $items = array();

    if($result && mysql_num_rows($result) > 0) { 
        while ($row = mysql_fetch_array($result)) { 
        $items[] = array("price"=>$row['price'], "day"=>$row['day'], "queue jump"=>$row['queue jump'], "closing"=>$row['closing'], "doors"=>$row['doors']);
        }
    } 

    mysql_close(); 
    // convert into JSON format and print

    echo json_encode($items);
?>

JS:

<script type="text/javascript">

    $(document).ready(function() {
// for simplicity's sake, but ultimately I'd like to load all the information
            $('#right_inside').html('<h2>' + $('#club').val() + '</h2>');
    });

    $('#club').change(function(event) {
        $.ajax({
            type: "post",
            url: "eventinfo.php",
            data:  $(this).serialize(),
            success: function(data) {
                $('#right_inside').html('<h2>' + $('#club').val() + '</h2><p>Day: ' + data.day + '</p>');
                },
            dataType: "json"
        });
    });

</script>
3
  • what is the result of the net request to eventinfo.php in firebug or just going to the site directly? Commented Jun 13, 2012 at 23:09
  • 1
    What does console.log(data) output when you add it to the success callback? Surely there will be a notice about an error... Commented Jun 13, 2012 at 23:09
  • 1
    try seeing the results of the ajax by JSON.stringify(data) Commented Jun 13, 2012 at 23:12

1 Answer 1

5

You have got your JSON structure wrong. Data is actually an array:

Try changing data.day to data[0].day

Note: You should use JSON.stringify(data) in your ajax success to see the structure of your JSON.

$.ajax({
  type: "post",
  url: "eventinfo.php",
  data:  $(this).serialize(),
  success: function(data) {
     alert(JSON.stringify(data));
     //or
     console.log(JSON.stringify(data));
  },
   dataType: "json"
 });
Sign up to request clarification or add additional context in comments.

1 Comment

This worked. Thanks very much - will accept as soon as I can.

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.