GenesisTepait
GenesisTepait

Reputation: 73

How to retrieve data that is sent by ajax in php?

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:

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"];?>';

           }

Upvotes: 0

Views: 104

Answers (1)

user9886608
user9886608

Reputation:

You have many errors in your code.

Errors in your retrieve_data.php

When you use AJAX, you don't use $_SESSION to exchange data; instead, you print the results like in a normal page but usually embeeded in a structured format like JSON or XML. What I recommend you is to organize everything that you are going to retrieve in an array and then use a coding function like json_encode.For example:

if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        $result["empName"] = $row['name'];
        $result["empPosition"] = $row['position'];
    }
} else {
    $result["empName"] = '0 results.';
    $result["empPosition"] = '0 results.';
}
//json encode prints the result formatted
exit(json_encode($result));

Errors in your html

First of all, when you use AJAX, you usually don't use forms, because the default behaviour of a form is to load the page; also the info of method and action is already beeing given in the open() method so you are beeing redundant(Also notice that you are telling the form to use POST while AJAX to use GET). Better use a button. If you have to use use forms, then always return false to prevent the page being loaded. Also, inside the onreadystatechange you must NOT use php's echo. Remember that PHP is a preprocesor and once in the client side everything printed is inalterable. You must to use the XMLHttpRequest properties responseText or responseXML. This properties contain the response received. If you follow my recommendation of using json_encode in you php file, then tou need to use JSON.parse to process the data received. Also in your query string don't use spaces So for example:

EMPLOYEE ID: <input type="text" name='emp_id' id='emp_id'/>
<button onclick="searchEmp()">Search</button>
<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) {
                jsonResponse = JSON.parse(xhr.responseText);
                document.getElementById('empName').innerHTML = jsonResponse.empName;
                document.getElementById('empPos').innerHTML = jsonResponse.empPosition;
            }
        }

        xhr.open("GET", "retrieve_data.php" + query, true);
        xhr.send(null);
    }
</script>

I recommend you to check basic AJAX documentation, because it seems that you have some confusion in some AJAX concepts.

https://www.w3schools.com/xml/ajax_intro.asp

Let me know if you have any more questions.

Upvotes: 1

Related Questions