0

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

           }
GenesisTepait
  • 63
  • 1
  • 10
  • Possible duplicate of [How to pass JavaScript variables to PHP?](https://stackoverflow.com/questions/1917576/how-to-pass-javascript-variables-to-php) – Loek Jun 06 '18 at 08:57
  • Do not session_start twice. it should be only once and in the start on file. – hanish singla Jun 06 '18 at 08:58
  • Please change `onClick` to `onSubmit` and add `event.preventDefault()` to stop the default action of the form .- – Aniketh Saha Jun 06 '18 at 09:08
  • @Loek Nope, I was really hopeful that I'd find my answer, but was disappointed. – GenesisTepait Jun 07 '18 at 01:09
  • @GenesisTepait note that SO is a community that does its level best to answer every question we can. Still, we can't actually answer everything. If Dknacht's explanation isn't working for you, do some more research and edit your question. Good questions tend to get good answers. – Loek Jun 07 '18 at 05:52

1 Answers1

1

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.

  • I just have discovered that my `if(xhr.readyState == 4)` does not even execute. Why? Is there any particular requirement for it to execute? I know that "4" is a numeric code which means "after the request has been completed, and the response data has been completely received from the server" but I guess it does not do that, am I missing anything? – GenesisTepait Jun 07 '18 at 03:18
  • Still the same. I have added an `alert(""+xhr.readystate)` below `xhr.send()`, it says 1. How is this making sense – GenesisTepait Jun 07 '18 at 03:36
  • No, you have a confusion. After the send() call, the script will finish. Then, when a change in the request occurs, JavaScript will call the onreadystatechange method asynchronously. If you put an alert() inside onreadystatechange (let's say, before `if (xhr.readyState == 4) {`) you will notice that this will be excecuted 4 times. I suggest that you put an alert(this.readyState) to see what you get. –  Jun 07 '18 at 03:44
  • I put an `alert(this.readyState)` before `(xhr.readyState == 4)` and it alerted 4 times with 1 as first alert, then 2,3 , and by the last time it was executed, my alert says 4. This confused me even more lol – GenesisTepait Jun 07 '18 at 04:02
  • That means all from the ajax request is Ok. Now, after `if (xhr.readyState == 4) {` put `alert(this.responseText)` and tell me what it shows. Probably you have some syntax error in your PHP so the JSON does not get back clear (is returned with some warning that does not allow to parse it properly) –  Jun 07 '18 at 04:06
  • Am I wrong to think that my PHP is not the case? because I have changed my `document.getElementById('empName').innerHTML = jsonResponse.empName; document.getElementById('empPos').innerHTML = jsonResponse.empPosition;` to `document.getElementById("empName").innerHTML = "NICE!" document.getElementById("empPos").innerHTML = "NICE!"` and it still doesn't work, this is what actually confused me. – GenesisTepait Jun 07 '18 at 05:11
  • quit the first two lines above and see if it works. I mean just leave document.getElementById("empName").innerHTML = "NICE!" document.getElementById("empPos").innerHTML = "NICE!" and let's see if it still wont work –  Jun 07 '18 at 22:19