I am trying to build a very simple web service using PHP. But I am unable to get response from the PHP (which is sending the data in a JSON format). When I print my responseText using console.log(), it shows as empty string. PHP is accepting some data using get method and when I enter PHP file and query parameter through url, data is displayed. I am unable to bring this data back to my HTML file. Please help me. I tried reading lots of question on https://stackoverflow.com/ and i also referred to lots of code and videos but cant find any solution yet
This is my HTML and Javascript code:
<html>
<head>
<title>Agent Details</title>
<head>
<body>
<form method="get">
<h1>Enter Agent ID</h1>
<input name="userd" id="userid" type="text" placeholder="enter agent id"></input><br>
<input type="submit">
</form>
<div id="display">
</div>
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(xhttp);
document.getElementById("display").innerHTML=xhttp.responseText;
}
};
xhttp.open("GET", "test.php", true);
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.send();
</script>
</body>
</html>
This is my PHP code:
<?php
$con = mysqli_connect("localhost","root","","raw");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_GET["userid"])){
$username=$_GET["userid"];
$query="SELECT * FROM agents WHERE agent_id='$username'";
$results=mysqli_query($con,$query);
$rows=mysqli_fetch_assoc($results);
$myJson=json_encode($rows);
header('Content-Type: application/json');
echo $myJson;
}
mysqli_close($con);
?>
Screenshots
This show when I directly access PHP file its echos output: php running successfully
Here you can see that communication is happening between client and web-service since status is "200" and status message is "OK". But when I access PHP through Ajax, responseText is empty response text shown as empty when used ajax call