I am still a student and I am really new to web development. I am currently learning ajax. I wanted to pass (via button) an ID to my PHP script for SQL processing, and display the data retrieved to my page without reloading it. But it doesn't seem to work. After I press the button, it visually loads the PHP page (which, in my own understanding, wasn't suppose to happen when using ajax).
HTML and JavaScript code:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
session_start();
?>
<form action="retrieve_data.php" method="POST" name="searchForm">
EMPLOYEE ID: <input type="text" name='emp_id' id='emp_id'/>
<input type="submit" value="Search" onsubmit="searchEmp()"/>
</form>
<br>
NAME:<p id="empName"></p><br>
POSITION:<p id="empPos"></p>
<script>
function searchEmp() {
var empID = document.getElementById('emp_id').value;
var query = "?emp_id = " + empID;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4) {
document.getElementById('empName').innerHTML = '<?php echo $_SESSION["empName"]; ?>';
document.getElementById('empPos').innerHTML = '<?php echo $_SESSION["empPosition"];?>';
}
}
xhr.open("GET", "retrieve_data.php" +query, true);
xhr.send(null);
};
</script>
retrieve_data.php:
<?php
session_start();
if(!empty($_GET["emp_id"])){
$_SESSION["emp_id"] = $_GET["emp_id"];
$emp_id = $_SESSION["emp_id"];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "overtimedtr";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM employees where id ='".$emp_id."'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$_SESSION["empName"] = $row['name'];
$_SESSION["empPosition"] = $row['position'];
}
} else {
echo "0 results";
}
mysqli_close($conn);
}
?>
Here's a picture of my html page:
What I am trying to do is when I click the search button, the page should display the name and the position without reloading the page in a <p>
element whose id's are "empName" and "empPos", the outcome isn't what i wanted, it displays my PHP page instead (which displays empty).
EDIT:
I have discovered that I don't need to add method="GET"
in the form, then the page did not have to refresh, just as what I have wanted.
<form name="searchForm">
EMPLOYEE ID: <input type="text" name='emp_id' id='emp_id'/>
<input type="submit" value="Search" onsubmit="searchEmp()"/>
</form>
The only remaining problem is that I could not seem to get the value of $_SESSION["empName"]
and $_SESSION["empPosition"]
from my PHP page. What could I have been getting wrong?
if(xhr.readyState == 4) {
document.getElementById('empName').innerHTML = '<?php echo $_SESSION["empName"]; ?>';
document.getElementById('empPos').innerHTML = '<?php echo $_SESSION["empPosition"];?>';
}