I execute the SQL query and I receive the array processed with fetch_assoc
. Finally in php
I return it through ajax with json_encode
.
echo json_encode($this->rows);
And this would be the code in JS:
function search(){ //recojo los datos y llamo a askDatabase
var id_vehicle = document.buscar.id_vehicle.value;
var brand = document.buscar.brand.value;
askDatabase(id_vehicle, brand);
}
function askDatabase(id_vehicle, brand){ //Comunicación con PHP
__ajax("controller.php?p=list/", "id_vehicle="+id_vehicle+"&brand="+brand)
.done( function( info ){
console.log("DATA: " + info);
info = JSON.parse(info); //AQUI EL ERROR
renderData(info);
});
}
function __ajax(url, data){ //Ajax configured
var ajax = $.ajax({
"method": "POST",
"url": url,
"data": data
})
return ajax;
}
I get the following string (var info)
, but I want an object:
[{"id_vehicle":"1","class":"business","brand":"Citroen","model":"C5 2.0hdi","year":"2010","km":"129000"}]
Which when attempting to parse, produces the following error, as reported by the chrome console:
Uncaught SyntaxError: Unexpected token in JSON at position 0
at JSON.parse (<anonymous>)
at Object.<anonymous> (controller.php:127)
at fire (jquery-3.1.1.js:3305)
at Object.fireWith [as resolveWith] (jquery-3.1.1.js:3435)
at done (jquery-3.1.1.js:9242)
at XMLHttpRequest.<anonymous> (jquery-3.1.1.js:9484)
How can I return the JSON object from PHP through ajax?