Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
52
rated 0 times [  56] [ 4]  / answers: 1 / hits: 30168  / 12 Years ago, sat, june 9, 2012, 12:00:00

How can I pass data from a php of then rows back to ajax ?



PHP



$query = 'SELECT * FROM picture order by rand() LIMIT 10';
$result = mysql_query($query);

while ($rec = mysql_fetch_array($result, MYSQL_ASSOC)) {

$url[]=$rec['pic_location'];
$name[]=$rec['name'];
$age[]=$rec['age'];
$gender[]=$rec['gender'];


}

echo json_encode($url);
echo json_encode($name);
echo json_encode($age);
echo json_encode($gender);


Ajax



$(.goButton).click(function() {
var dir = $(this).attr(id);
var imId = $(.theImage).attr(id);

$.ajax({
url: viewnew.php,
dataType: json,
data: {
current_image: imId,
direction : dir
},
success: function(ret){
console.log(ret);
var arr = ret;
alert(first image url: + arr[0][0] + , second image url: + arr[0][1]); // This code isnt working
alert(first image Name: + arr[1][0] + , second image name: + arr[1][1]);
$(.theImage).attr(src, arr[0]);
if ('prev' == dir) {
imId ++;
} else {
imId --;
}
$(#theImage).attr(id, imId);
}
});

});
});
</script>


My question is how can I display the values here ? The Alert message is giving me Undefined ?


More From » php

 Answers
30

You can do something along these lines.



PHP



$query = 'SELECT * FROM picture order by rand() LIMIT 10';
$res = mysql_query($query);

$pictures = array();
while ($row = mysql_fetch_array($res)) {
$picture = array(
pic_location => $row['pic_location'],
name => $row['name'],
age => $row['age'],
gender => $row['gender']
);
$pictures[] = $picture;
}

echo json_encode($pictures);


JS



...
$.ajax({
...
dataType: json,
...
success: function(pictures){
$.each(pictures, function(idx, picture){
// picture.pic_location
// picture.name
// picture.age
// picture.gender
});
}
});
...

[#85029] Friday, June 8, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
conorm

Total Points: 339
Total Questions: 104
Total Answers: 104

Location: Angola
Member since Tue, May 5, 2020
4 Years ago
;