user2669997 user2669997 - 3 months ago 8
Ajax Question

json ajax update HTML element not working

I am trying to get a HTML element to update from an ajax quire to a PHP file but it's not working.
My code is below



<html>
<head>
<script src="jquery-3.1.0.min.js"></script>
</head>

<body>

<script>
var json = (function () {
var json = null;
$.ajax({
url: "test.php",
dataType: "json", //the return type data is jsonn
success: function(data){ // <--- (data) is in json format
json = data.test;
$('#demo').text(json.test1);
}
});
return json;
})();
</script>
<p id="demo"></p>
</body>
</html>





PHP code

<?php
header("Content-Type: application/json");

$test = array();
$test['test1'] = '1';
$test['test2'] = '2';
$test['test3'] = '3';

echo json_encode($test);
//echo nothing after this //not even html
?>


can someone please help, thank you

Answer

Your php script sending a JSON object and you can access its property like this:

$.ajax({
  url: "test.php",
  dataType: "json", //the return type data is jsonn
  success: function(data){ // <--- (data) is in json format
    $('#demo').text(data.test1);
}
});