I want to import data from the database into my javascript code, using ajax through jQuery, but I got a json parse error and I really don't know what it does come from. Could you help me ?
The goal is to build buildings on a map, and i take the geometry elements such as coordinates and shape parameters from the database.
in the JS file, put:
$.ajax({ type: "GET", url: "ajax_processor.php", dataType : "html", error:function(msg, string){ alert( "Error !: " + string ); } success:function(returnData){ var data = $.parseJSON(returnData); for(var ID_geometryElement in data) { addComp($data[bldg], $data[iZ], // zone where is the building $data[iType], //type of the geometric element $data[x0], $data[y0],//coordinates top-left $data[p], // geometric parameters ); } } });});
in the PHP file:
try { $bdd = new PDO('mysql:host=localhost;dbname=building_geometry','admin','password'); } $reponse = $bdd->query('SELECT * FROM ID_GEOMETRYELEMENT'); $donnees = $reponse->fetch(); header('Content-Type: application/json'); echo json_encode($response); ?>
3 Answers 3
You're trying to json_encode the database statement handle your query returned. That is NOT something you can encode. The code should be
echo json_encode($donnees);
^^^^^^^^--- the actual data
If you'd done even the most basic debugging, e.g. console.log(returnData) in JS, you'd have seen you're not getting anything valid returned from the script.
dataType : "html",
must be
dataType : "json",
if you expect JSON in the response
EDIT: See http://api.jquery.com/jQuery.post/
dataType
Type: String
The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html).
2 Comments
$response is just a cursor, you need to return the fetched data.
try {
$bdd = new PDO('mysql:host=localhost;dbname=building_geometry','admin','password');
}
$reponse = $bdd->query('SELECT * FROM ID_GEOMETRYELEMENT');
$donnees = $reponse->fetch();
header('Content-Type: application/json');
echo json_encode($donnees);
?>
for(var ID_geometryElement in data) {then you getting each item inID_geometryElementvariable, not in$data(and from where you get $ sign in JS var?).json_encode()? What does the browser show in the http response data? Also, in your JS code, you appear to have a variable nameddata, but it looks like you're referring to it by the name$data. That looks like a bug.