A weird thing is happening when I execute a function that "alerts" data from a json. If I specify, like alert(data.name);
, the "Alert" returns "Undefined", but if I just put alert(data);
, it returns the object like {"id":"1","name":"Erluan"}
This is the function that receives an id to search in the database
function receiveUser(val){
$.ajax({
type:"POST",
url:"../json/userperm/userGrid.php",
data: 'iduser='+val,
datatype:"json",
success: function(data, string, jqXHR){
alert(data.name);
}
});
}
And this is the userGrid.php
<?php
include('../../config.php');
$user = mysql_query("SELECT * from hospital_".$_SESSION['template'].".users where id = ".$_POST['iduser']." order by name");
$results = array();
while($row = mysql_fetch_array($user))
{
$results[] = array(
'id' => $row['id'],
'name' => $row['name']
);
}
$json = json_encode($results);
echo $json;
?>
Thank you.
Returning JSON from a PHP Script
Your php script needs the correct header:
header('Content-Type: application/json');
It seems JQuery is intrepteing the result as the string {"id":"1","name":"Erluan"}, by having the correct header it should then be parsed as JSON.
Have you tried evaluating the ajax response? If not then try to call eval function and then fetch the values.
success: function(data, string, jqXHR){
var res = eval('(' + data+ ')');
alert(res.name);
}