Can't receive PHP object by using AJAX


Can't receive PHP object by using AJAX



I can't fetch the php file from the ajax. Firstly an object is created in the PHP file, then it is converted into JSON by using json_encode() function. The problem is: when I request that PHP file from ajax, nothing is shown as an output. ('Smith' is supposed to be an output though)



Here is my php file: 1.php


<?php
$myObj->name = "Smith";
$myObj->age = 20;
$myObj->Address = "Yangon";

$myJSON = json_encode($myObj);

echo "$myJSON";
?>



Here is ajax file: ajaxfile.php


<p id="demo"></p>
<script type="text/javascript">
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj.name;
}
};
xmlhttp.open("GET", "1.php", true);
xmlhttp.send();
</script>





Have you tried looking at your browser's network console? What do you see there? Is the request executed properly? Does the response logged there look like expected? If you call console.log(myObj), what does it contain?
– Nico Haase
Jul 1 at 7:28


console.log(myObj)





Some changes in the syntax of PHP object make it works now. ($myObj->name = "Smith"; to $myObj['name'] = "Smith";).
– Sat Naing
Jul 1 at 8:12





1 Answer
1



Try


<?php
$myObj['name'] = "Smith";
$myObj['age'] = 20;
$myObj['Address'] = "Yangon";
$myJSON = json_encode($myObj);

echo "$myJSON";
?>






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

List of Kim Possible characters

Audio Livestreaming with Python & Flask

NSwag: Generate C# Client from multiple Versions of an API