Im trying to get a PHP file to execute a MySQL query and return the results in a JSON format to a Javascript function.
My php:
require_once("class.user.php");
$auth_user = new USER();
$stmt = $auth_user->runQuery("
SELECT *
FROM projects;
");
$stmt->execute();
$results=$stmt->fetchall(PDO::FETCH_ASSOC);
file_put_contents('filename.json',json_encode($results));
header('Content-type: application/json');
echo json_encode($results);
My Javascript:
function getProjectNames(){
var dataList = document.getElementById('projectNames');
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
IsJsonString(this.response);
//document.getElementById("projectsresults").innerHTML = this.response;
}
};
xmlhttp.open("GET","getProjectNames.php",true);
xmlhttp.send(null);
}
function IsJsonString(str) {
try {
document.write(JSON.stringify(str));
} catch (e) {
document.write("is not valid JSON" + e);
return false;
}
//document.write("is valid JSON");
return true;
}
Now the javascript will display
[{"Project_ID":"1","Name":"Software Project 1"},{"Project_ID":"2","Name":"Software Project 2"}]
However if i try to parse this as JSON and access a variable then it either comes back with 'undefined' or 'null'. I have tried 'JSON.stringify' and that returns
"
[{\"Project_ID\":\"1\",\"Name\":\"Software Project 1\"},{\"Project_ID\":\"2\",\"Name\":\"Software Project 2\"}]
"
So i think something must be going wrong between the PHP encoding the JSON and the Javascript fetching it. I have ran out of ideas and any help would be appreciated.
Edit: Added the rest of PHP and Javascript code
Try using this instead of your IsJsonString function:
function IsJsonString(response){
var parsedJson = JSON.parse(response);
var jsonString = JSON.stringify(parsedJson);
document.getElementById("projectNames").innerHTML = jsonString;
}
and pass it this.response
as a parameter.