Rohit
Rohit

Reputation: 51

Not able to fetch json data from a php file in localhost

I am trying to make a client side script to fetch JSON data from a PHP file. I am using XAMPP to run the PHP scripts. When I run the demo_file.PHP, it shows the output. But when I try to fetch the data using the client side script it does not show any result. The demo_file.php is:

<?php
$myObj->name = "John";
$myObj->age = 30;
$myObj->city = "New York";

$myJSON = json_encode($myObj);

echo $myJSON;
?>

and the demo.html to fetch the json data is:

<!DOCTYPE html>
<html>
<body>

<h2>Get data as JSON from a PHP file on the server.</h2>

<p id="demo"></p>

<script>

var xmlhttp = new XMLHttpRequest();

xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        myObj = JSON.parse(this.responseText);
        document.getElementById("demo").innerHTML = myObj.name;
    }
};
xmlhttp.open("GET", "demo_file.php", true);
xmlhttp.send();

</script>

</body>
</html>

Upvotes: 1

Views: 299

Answers (1)

Hikmat Sijapati
Hikmat Sijapati

Reputation: 6994

You probably getting error:

<b>Warning</b>:  Creating default object from empty value in <b>[...][...]</b> on line <b>3</b><br />

You can not create object directly like this.You have create instance of StdClass() first.Like below.

$myObj = new stdClass();//need to create instance first
$myObj->name = "John";
$myObj->age = 30;
$myObj->city = "New York";

$myJSON = json_encode($myObj);

echo $myJSON;

For more see here Creating default object from empty value

Upvotes: 1

Related Questions