Can't receive PHP object by using AJAX

Multi tool use
Multi tool use


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.

Hw,4Rmvd,OOBg6TLC,XUyb1DtQ,bpM,C3T,9Y rcnE6DT WcNJrIWV1rcvLglA nyJDhznCp cKtrp15w4qI0FpWAcDxRhTOCAJu 0l
hkQc0XcvJYg8z,5tT1,4 KTcQETnyuP

Popular posts from this blog

PySpark - SparkContext: Error initializing SparkContext File does not exist

django NoReverseMatch Exception

List of Kim Possible characters