I'm trying to get a JSON from a PHP page, but always I receive 'undefined'.
My jQuery code is:
<script>
$(document).ready(function(){
$("#lista_partecipanti").click(function(){
$.post( "application/third_party/php_files/lista_partecipanti.php",
{
user_id:<? echo $user_id; ?> , jam_id:<? echo $id_jam; ?>
},
function(data)
{
if(data) {
$("#div_lista_partecipanti").html('test' + data[0].username);
}
else
{
alert("Error");
}
});
});
});
</script>
My PHP code is:
<?php
include 'db_connect.php';
$a_id = $_POST['user_id'];
$b_id = $_POST['jam_id'];
$query = mysql_query("SELECT * FROM User a, Jam b WHERE a.id = b.owner AND a.id = $a_id AND b.id = $b_id");
if(mysql_num_rows() == 1)
{
$row = mysql_fetch_assoc($query);
$data = array(
'username' =>$row['username'],
'user_id' => $row['id']
);
$data = json_encode($data);
echo $data;
}
else
return false;
mysql_close();
?>
Solved
I solved my problem, it was not a PHP problem but the error was in the jquery code. I just added
data = $.parseJSON(data);
before
$("#div_lista_partecipanti").html(data.username);
3 Answers 3
Since you haven't specified otherwise, so PHP will claim that it is outputting an HTML document, and jQuery will treat the JSON as if it were HTML.
Add header("Content-Type: application/json");
before you output anything from your PHP.
Secondly, your JSON text consists of a single object, not an array of objects.
data[0].username
should be just data.username
Comments
First you're very open to mysql injection, you should use mysqli or pdo prepared statements.
Second you shouldn't echo JSON inside the loop, it doesn't work like that, you need to add all your data to an array and then json_encode
it and return it after the loop, although for your example it's only one item but still.
<?php
include 'db_connect.php';
header("Content-Type: application/json");
$a_id = $_POST['user_id'];
$b_id = $_POST['jam_id'];
$query = mysql_query("SELECT * FROM User a, Jam b WHERE a.id = b.owner AND a.id = $a_id AND b.id = $b_id");
if(mysql_num_rows() >= 1) {
$data = array();
while($row = mysql_fetch_assoc($query)){
$data[] = array(
'username' =>$row['username'],
'user_id' => $row['id']
);
}
echo json_encode($data);
} else {
echo json_encode([]);
}
mysql_close();
5 Comments
jQuery.ajax({
type: "POST",
url: "application/third_party/php_files/lista_partecipanti.php",
data: "userid="+<?php echo $user_id; ?>+"&jam_id="<?php echo $id_jam; ?>,
cache: false,
success: function(response) {
...
}
}
);
while
loop is rather distracting - you've established there is only one row.