Ajax is commonly used to fetch data from the server.
The data is successfully displayed in an alert as
data: {"status": "Active","broadcastmsg": "msg"}
However, when displayed in HTML i.e. <p id="demo"></p>
, it shows up as undefined.
This seems like a minor issue but I have been trying to resolve it for the past 24 hours with no success. Any suggestions on what might be going wrong would be greatly appreciated.
Client.php
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<body>
<script>
function myFunction(val) {
$.post("test.php",
{
d_id: 1,
date: val
},
function(hstatus){
alert(hstatus);
myJSON = JSON.stringify(hstatus);
localStorage.setItem("testJSON", myJSON);
//Retrieving data:
text = localStorage.getItem("testJSON");
obj = JSON.parse(text);
document.getElementById("demo").innerHTML = obj.status;
});
}
</script>
<p id="demo"></p>
<div id="future_date" style="display:block;" class="col-xs-12">
<input type="date" name="txt" value="" onchange="myFunction(this.value)">
</div>
</body>
</html>
EDIT
If we manually pass
hstatus = {"status": "Active","broadcastmsg": "msg"}
, it displays the result properly.
Therefore, the issue lies in converting from
data: {"status": "Active","broadcastmsg": "msg"}
to
{"status": "Active","broadcastmsg": "msg"}