1

i want to retrive json data from php with ajax and output it for test. but it did not work.

Client index.php

<html>
<head>
<title>kakak</title>
</head>
<body>
<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", "json.php", true);
xmlhttp.send();

</script>
</body>
</html>

And this's json.php already have object.

<?php

$myArray = ["name" => "john", "age" => 30, "city" => "Japan"];

$myObj = json_encode($myArray);

?>

I want to retrieve object name but it dont ouput anything.

10
  • @TheCodesee what do you mean anyway? object i want retrieve in json.php. Commented Mar 12, 2017 at 9:07
  • @TheCodesee {"name":"john","age":30,"city":"Japan"} this's the object. Commented Mar 12, 2017 at 9:11
  • So this is what you should receive in js. Commented Mar 12, 2017 at 9:11
  • Use "JSON.parse()" in js. Commented Mar 12, 2017 at 9:12
  • @hossam i already use it in my ajax call. but it return nothing. can u look my client code? Commented Mar 12, 2017 at 9:13

1 Answer 1

3

You need to echo the JSON string in PHP code.

echo $myObj;

Final code would be:

<?php

$myArray = ["name" => "john", "age" => 30, "city" => "Japan"];
$myObj = json_encode($myArray);
echo $myObj;
// or directly
// echo json_encode($myArray);
?>
Sign up to request clarification or add additional context in comments.

2 Comments

thanks, by the way. by your respective. is it safe to use json data in client side? i plan to convert mysql database to json and play in client side for validating data when login and activation. is it safe?
@jarwobangun : what you mean by "client side for validating" ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.