1

In json.php:

$data = array ( "filename"  => array (), "datetime"  => array () );

The $data array is filled with some data from a loop.

In index.php:

$.ajax({
    url: "json.php",
    success: function(data){

        $.each(data, function(i, item) {
            console.log(data[i].filename);
        });



     }
});

I'm trying to print all the filenames from my data object, but they're undefined according to the console. What did I miss?

1
  • plz accept one of the answers if it solved your problem, thx Commented Apr 23, 2011 at 15:14

3 Answers 3

2

on php site:

$data = array ( "filename"  => array (), "datetime"  => array () );
header('Content-type: application/json');
echo json_encode($data);
exit;

on js site:

$.ajax({
    url: "json.php",
    dataType: "json",
    success: function(data){

        $.each(data, function(i, item) {
            console.log(item.filename);
        });

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

Comments

1

You should use json_encode($data).

Comments

0

I'm not a PHP developer, but have you checked data using Firebug because it's probably not JSON?

If you find out that it's a JSON string you should first do this

data = $.parseJSON(data);

And for the sake of brevity you could write

$.ajax({
    url: "json.php",
    success: function(data){
        data = $.parseJSON(data); // if needed
        $.each(data, function() {
            console.log(this.filename);
        });
     }
});

Comments

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.