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);