I am attempting to obtain PHP data from my Javascript code. This is meant to be shown in the dayta
div id. What I end up getting instead is undefined
instead of the desired result (which in this instance is the firstname
in my JSON file). I am not sure why this is happening.
My JavaScript code:
window.onload = function(){
var http = new XMLHttpRequest();
http.onreadystatechange = function(){
if (http.readyState == 4 && http.status == 200){
var dayta = document.getElementById('datadisplay');
dayta.innerHTML = http.response.firstname;
}
}
http.open("GET", "myphpfile.php", true);
http.send();
}
My PHP code (myphpfile.php
):
<?php
$content = file_get_contents('somejsonfile.json');
print_r($content);
$dbcon->close();
?>
The PHP code included is only a portion of my code, but it contains all the parts relevant to my problem.
$content
outputs a JSON file, as that is what it is pointed to. If I echo $content
I am able to verify that the content is streamed out as intended.
Thus, the problem is most likely with my JavaScript code. But I cannot identify specifically what is wrong.
My JSON file (somejsonfile.json
):
{"firstname": "Ki ki ki ma ma ma"}
I understand that the most obvious way to approach this specific example is to simply have the JavaScript file reach the JSON file. However, since I'm trying to secure the path of my JSON file in my production code I am trying out this method.
Make sure you get a JSON response by using JSON.parse
. Here's a quick solution. I have tried it and it works great!
window.onload = function(){
var http = new XMLHttpRequest();
http.onreadystatechange = function(){
if (http.readyState == 4 && http.status == 200){
var dayta = document.getElementById('datadisplay');
var data = JSON.parse(http.responseText);
dayta.innerHTML = data.firstname;
}
}
http.open("GET", "myphpfile.php", true);
http.send();
}
pls check this code;
<?php
$content = file_get_contents('somejsonfile.json');
print_r(json_decode($content));
?>
if you see array truly then,
<?php
$content = file_get_contents('somejsonfile.json');
echo(json_encode($content));
?>
if you want to query in json file, you can use json_decode function to convert array and push or remove array item and then json_encode.