1

I have this php script which when run outputs this. I cannot seem to fathom out how to access this in jquery I have tried varous methods from tutorials but no avail.

{"name":"photo1.jpg","id":"1"}{"name":"photo2.jpg","id":"2"}
{"name":"photo3.jpg","id":"3"}{"name":"photo4.jpg","id":"4"}

<?php

mysql_select_db('news') or die(mysql_error());
//echo "Connected to Database";<?php 

$result = mysql_query("SELECT * FROM photos") 
or die(mysql_error());  

// keeps getting the next row until there are no more to get
while($row = mysql_fetch_assoc( $result )) {    
    echo json_encode($row);
} 
?>

Jquery

$(document).ready(function() {                      
$.getJSON('photo_get.php', function(data){

alert("Data" + data.name);

});
});

This outputs nothing.


Thanks for any help.

3 Answers 3

2

This is not valid JSON:

{"name":"photo1.jpg","id":"1"}{"name":"photo2.jpg","id":"2"}

It should look like this:

[{"name":"photo1.jpg","id":"1"},{"name":"photo2.jpg","id":"2"}]

What you should do is to push every row to some array and then serialize the entire array to JSON.

Eg. use something like this in the loop:

$array[] = $row;

and then serialize the whole thing outside of the loop:

echo json_encode($array);
Sign up to request clarification or add additional context in comments.

Comments

1

i think it should be

<?php
$rows=array();
mysql_select_db('news') or die(mysql_error());
//echo "Connected to Database";<?php 

$result = mysql_query("SELECT * FROM photos") 
or die(mysql_error());  

// keeps getting the next row until there are no more to get
while($row = mysql_fetch_assoc( $result )) {    
    $rows[]=$row;
} 
echo json_encode($rows);
?>

$(document).ready(function() {                      
$.getJSON('photo_get.php', function(data){
$.each(data, function(key, val) {
alert("Data" + val.name);
});
});
});

as its an array

1 Comment

The php file now outputs [{"name":"photo1.jpg","id":"1"},{"name":"photo2.jpg","id":"2"},{"name":"photo3.jpg","id":"3"},{"name":"photo4.jpg","id":"4"}] But still no Alertbox
0

you can push your response to array:

ArrayData = [];

ArrayData = data;

and then loop it:

for (var i; i < ArrayData.length; i++) {
   alert(ArrayData[i]['name'])
}

1 Comment

isint that what $.each(data does ?

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.