0

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

jps
  • 20,041
  • 15
  • 75
  • 79
  • 1
    Your code is vulnerable to [**SQL injection**](https://en.wikipedia.org/wiki/SQL_injection) attacks. You should use prepared statements with bound parameters, via either [**mysqli**](https://secure.php.net/manual/en/mysqli.prepare.php) or [**PDO**](https://secure.php.net/manual/en/pdo.prepared-statements.php). [**This post**](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) has some good examples. – Alex Howansky Apr 04 '18 at 13:59
  • thanks @AlexHowansky – harshad vaviya Apr 04 '18 at 14:57

2 Answers2

1

You're not passing any parameters in your AJAX query: xhttp.open("GET", "test.php", true);. In the PHP example screenshot, you're passing userid as a GET parameter: test.php?userid=1.

Máté Safranka
  • 4,081
  • 1
  • 10
  • 22
  • I edited my code as `xhttp.open("GET","test.php?userid="+getElementById("userid").value, true);` but the problem now arising is this script is executed as the page loads and not when the form is submitted and as @elfu suggested to use a function and call it. I did that too but now what's happening is function is called and executed once only and the result which is displayed using DOM inside function disappears quickly. Please help me – harshad vaviya Apr 04 '18 at 15:05
  • This is a much longer topic than what SO questions are for. You need to learn in depth how forms and scripts work. Try reading up on MDN: https://developer.mozilla.org/en-US/docs/Learn/JavaScript – Máté Safranka Apr 04 '18 at 15:21
0

First: You are not passing any params via AJAX in line:

xhttp.open("GET", "test.php", true);

Second: You are sending when the page starts, and does not have a value defined in the field, the correct manner would be create a function with, call it when the button is pressed (remove the SUBMIT value for TYPE, and replace it with BUTTON), then call a function, like this:

<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="button" onclick="ajax()" value="submit">
</form>
<div id="display">
</div>
<script>
function ajax(){
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?userd="+document.getElementById('userid').value, true);
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.send();
}
</script>
</body>
</html>

Hope it helps!

Cauêh Q.
  • 104
  • 1
  • 2
  • I thought passing parameters through URL would be enough and I used `
    ` for that. I tried this code to pass parameter in AJAX call `xhttp.open("GET","test.php?userid="+getElementById("userid").value, true);` but it is unsuccessfull. Then I did this `xhttp.open("GET","test.php?userid=1", true);` Then it successfully displays first row but what happening here is result is getting displayed as soon as the page loads so i tried to put it into function as you said but then it displays results but in a flash results disappears.
    – harshad vaviya Apr 04 '18 at 14:54
  • I think that you've left your old `var xhttp = new XMLHttpRequest();` and the `xhttp.onreadystatechange = function() { ... }`. If that's the case then just remove it, the function should do the trick. If that's not the case, then post your code so I can investigate. – Cauêh Q. Apr 06 '18 at 14:41