简体   繁体   中英

Why does PHP AJAX work as from second click only?

New to PHP and AJAX.

I made a basic page whereby when I click a button, a php page will connect to a database and return me the name of the person whose age is 45 (already included in the url when sending).

My only issue is, it works only as from the second time I click the button. Help please?

My code for ajax.html and ajax-example.php below:

<!DOCTYPE html>
<html>
   <body>

    <script type="text/javascript">
        ajaxRequest = new XMLHttpRequest();
        function ajaxFunction() {
            ajaxRequest.onreadystatechange = reaction();
            ajaxRequest.open("GET","ajax-example.php?age=45", true);
            ajaxRequest.send(null);
        }

        function reaction() {
            if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
               alert(ajaxRequest.responseText);
            }
        }
     </script>

      <button onclick="ajaxFunction();">Click me</button>

   </body>
</html>

<?php
   $server = "localhost";
   $user = "root";
   $password = "";
   $db = "ajaxtrial";

  $conn = mysqli_connect($server,$user,$password,$db);

  if (!$conn) {
      die('Failure to connect!');
  }

  $age = $_GET['age'];

  $sql = "SELECT name FROM ajax_example WHERE age =".$age;

  $result = mysqli_query($conn, $sql);

  while ($row = mysqli_fetch_assoc($result)) {
   $display = "The name is ".$row['name'];
  }

  echo $display;
?>

Remove the parenthesis for the reaction method that you are assigning to onreadystatechange .

<script type="text/javascript">
    ajaxRequest = new XMLHttpRequest();
    function ajaxFunction() {
        ajaxRequest.onreadystatechange = reaction;
        ajaxRequest.open("GET","ajax-example.php?age=45", true);
        ajaxRequest.send(null);
    }

    function reaction() {
        if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
           alert(ajaxRequest.responseText);
        }
    }
 </script>

OR you can initialize an anonymous function to onreadystatechange .

 <script type="text/javascript">
    ajaxRequest = new XMLHttpRequest();
    function ajaxFunction() {
        ajaxRequest.onreadystatechange = function(){
           if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
               alert(ajaxRequest.responseText);
           }
        }
        ajaxRequest.open("GET","ajax-example.php?age=45", true);
        ajaxRequest.send(null);
    }
 </script>

I hope that helps you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM