Home > Net >  Using XMLHttpRequest to send Javascript variable to PHP to query MySQL. Not working
Using XMLHttpRequest to send Javascript variable to PHP to query MySQL. Not working

Time:06-21

I'm trying to query my MySQL database. The Javascript code in my html file is ...

<script>
function getGameNumberOfPlays() { 
   var sentValue1 = Number;   
   var xhttp;
   xhttp = new XMLHttpRequest();
   xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
         document.getElementById("gameNumberOfPlays").innerHTML = this.responseText;
      }
   };
   xhttp.open("GET", "numberOfPlays.php", true);
   xhttp.send(sentValue1);
}
</script>

The 'numberOfPlays.php' code is ...

<?php
$dbhost =   'localhost';
$dbuser =   'xxx'; 
$dbpwd  =   'xxx'; 
$dbname =   'xxx';

$conn   =   new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );

$p1 = $_GET['sentValue1'];

$sql= "SELECT COUNT(ID) FROM `data` WHERE `gameNumber` =  ?";

$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $p1);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_array();
echo "$user[0]";
$conn->close();

?>

The code above produces 0 in my html page.

However, if I change the code of 'numberOfPlays.php' to ...

<?php
$dbhost =   'localhost';
$dbuser =   'xxx'; 
$dbpwd  =   'xxx'; 
$dbname =   'xxx';

$conn   =   new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );

$p1 = $_GET['sentValue1'];

$p2 = 171; // or any number that's in the database

$sql= "SELECT COUNT(ID) FROM `data` WHERE `gameNumber` =  ?";

$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $p2);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_array();
echo "$user[0]";
$conn->close();

?>

I get the correct number in my html page so it appears that the coding is OK except for how the variable 'sentValue1' is sent and received.

I'd be very grateful if anyone could let me know how to change the code so that MySQL query works with the variable 'sentValue1'.

The 'gameNumber' column in the database is configured like this ...

Screenshot of column 'gameNumber'

Many thanks.

CodePudding user response:

You did not send the sentValue1 in your xhttp request

change:

xhttp.open("GET", "numberOfPlays.php", true);
xhttp.send(sentValue1);

to:

let URL = "numberOfPlays.php?sentValue1=<number>"; 
xhttp.open("GET", URL, true); 
xhttp.send();

or:

xhttp.open("GET", "numberOfPlays.php", true);
xhttp.send(sentValue1=<number>);

You can check this link

  • Related