Hybreeder Hybreeder - 2 months ago 37
JSON Question

How to display multiple values from AJAX in PHP?

I have to display multiple values from AJAX but I am getting only single value.

Concept:
The user will select single or multiple check box and according to the checkbox, it will display the image and user_id. I am able to display the image but not able to display the user_id. Would you help me in this?

I just upload only AJAX and PHP code

AJAX

$.ajax({
type: "POST",
url: "includes/compare_process.php", //
data:'users='+arr,
dataType: 'json',
success: function(msg){
$("#pics_name").empty();
$.each(msg, function() {
$("#pics_name").append("<img src='images/profile/" + this + "' alt='' />");
$("#pics_Id").append();//I have to display id here
});
},
error: function(){
alert("failure");
}
});


PHP

$_SESSION['compare_user']=$_POST['users'];
$sql_compare='SELECT * FROM request WHERE Id IN (' .( is_array( $_SESSION['compare_user'] ) ? implode( ',', $_SESSION['compare_user'] ) : $_SESSION['compare_user'] ).')';
$compare_query=$conn->query($sql_compare);
if ($compare_query->num_rows > 0) {
while($userdata12=$compare_query->fetch_assoc()){
$compare_pic[]=$userdata12['profile_pic'];
$compare_Id=$userdata12['Id'];
}
}
echo json_encode($compare_pic, $compare_Id);
exit();

Answer Source

You're not putting $compare_Id into an array. You need to create a 2-dimensional array in the PHP.

$_SESSION['compare_user']=$_POST['users'];
$sql_compare='SELECT id, profile_pic FROM request WHERE Id IN (' .( is_array( $_SESSION['compare_user'] ) ? implode( ',', $_SESSION['compare_user'] ) : $_SESSION['compare_user'] ).')';
$compare_pic = array();
$compare_query=$conn->query($sql_compare);
if ($compare_query->num_rows > 0) {
     while($userdata12=$compare_query->fetch_assoc()){ 
            $compare_pic[]=$userdata12;
     }
   }
echo json_encode($compare_pic);
exit();

Then access each property in the Javascript.

$.ajax({
    type: "POST",
    url: "includes/compare_process.php", // 
    data:'users='+arr,
    dataType: 'json',
    success: function(msg){
        $("#pics_name,#pics_Id").empty();
        $.each(msg, function() {
            $("#pics_name").append("<img src='images/profile/" + this.profile_pic + "' alt='' />");
            $("#pics_Id").append("<div>" + this.id + "</div>");
        });
    },
    error: function(){
        alert("failure");
    }
});