I have a function that return array object from php using mysql and i want call array from ajax function using javascript, but i don't know how display array object php in javascript dinamic table or console log....
my php file:
$age = $_POST["param"]; //value ajax param
$list = BussinesLayer::getUsers($age); //load my list
//list properties ej: list->getName(), getAge(), getOcupation()->getDescription(), etc..
echo json_encode($list);
my js function:
fnListUsers: function() {
var agedata = $("#txtAge").val();
$.ajax({
type : "POST",
url : "../ControllerFile/SearchUsers.php",
data : {"param" : agedata},
dataType : 'json',
success : global.fnSuccessList,
error : function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "
Status: " + textStatus + "
Error: " + errorThrown);
}
});
},
fnSuccessList: function(data) {
var array = JSON.parse(data); // -> dont work Uncaught SyntaxError: Unexpected token o in JSON at position 1
var array2 = jQuery.parseJSON(data); // dont work Uncaught SyntaxError: Unexpected token < in JSON at position 0
//how display my arrayobject ?
console.log(data.getName, data.getOcupation.getDescripition);
}
Your success function already has the data
in json format. So you don't need to parse it again in JSON. just use console.log(data)
to see your object.
fnSuccessList: function(data) {
var array = JSON.parse(data); // remove this
var array2 = jQuery.parseJSON(data); // remove this
console.log(data);
}
Here you are doing wrong you used dataType : 'json'
that already parsed data but after that you are again try to parse. that is causing error.
fnListUsers: function() {
var agedata = $("#txtAge").val();
$.ajax({
type : "POST",
url : "../ControllerFile/SearchUsers.php",
data : {"param" : agedata},
dataType : 'JSON',
success : global.fnSuccessList,
error : function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "
Status: " + textStatus + "
Error: " + errorThrown);
}
});
},
fnSuccessList: function(data) {
// this will show your data
console.log(data);
/* Don't use this just access data directly
var array = JSON.parse(data); // -> dont work Uncaught SyntaxError: Unexpected token o in JSON at position 1
var array2 = jQuery.parseJSON(data); // dont work Uncaught SyntaxError: Unexpected token < in JSON at position 0
*/
}
see in console if your data looks like this then it's parsed