I'm new at AJAX and I am just trying to display the database results from PHP to HTML via AJAX. I'm getting "undefined" on console log when I load the page. HTML, PHP and the JS files are separated from each other.
Here's my JS Code:
$(document).ready(function(){
$.ajax({
type: "GET",
url: "xaja.php",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data){
console.log(""+data.name);
},
error: function(e){
alert("Error:\n"+e);
}
});
});
Here's my PHP Code:
<?php
$json = array(
'username' => '',
'name' => '',
'loc' => ''
);
$sql = "Select * from tbluser";
$query = mysql_query($sql, $conn);
$result = mysql_fetch_assoc($query);
do{
$json['username'] = $result['username'];
$json['name'] = $result['name'];
$json['loc'] = $result['location'];
echo json_encode($json);
$result = mysql_fetch_assoc($query);
}
while($result);
?>
Am I missing something here? Thanks in advance!
console.loginstead ofalertto debug Javascript -alertonly handles strings or string-like values,console.logcan output nearly anything. You'll be able to see what the value ofeis (an object) and debugging will become much easier.