Ryan Webb Ryan Webb - 1 year ago 81
Ajax Question

Using HTML forms values for AJAX/PHP MySqli query

I am trying to use AJAX with both php and MySqli to get results from a database. I am very new to ajax and javascript so any help will be appriciated

This is my form:

<form method="get">
<input type="number" min=0 name="gameId" id="gameId" placeholder="Game Id" required><br>
<input type="number" min=0 step=0.01 name="price" id="price" placeholder="Price" required><br>
<button type="submit" onClick="getGames()">Submit</button>

This is my AJAX in JS:

function getGames() {
var gameId = document.getElementById("gameId").value;
var price = document.getElementById("price").value;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("jumbotron").innerHTML = xmlhttp.responseText;
xmlhttp.open("GET","getGames.php?gameId="+gameId+"&price="+price, true);

And this is my php

$servername = "localhost";
$serverusername = "root";
$dbname = "ryangames";

$gameId = intval($_GET["gameId"]);
$price = intval($_GET["price"]);

$conn = mysqli_connect($servername, $serverusername, "", $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());

$sql = "SELECT * FROM GAMES WHERE GameId = ".$gameId." AND Price = ".$price;
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "<div class=\"gameHolder\">
<img class=\"gameImg\" src=\"images/".$row["Code"].".png\" alt=\"".$row["Name"]."\">
<div class=\"gameText\">
<h3 class=\"gameName\">".$row["Name"]."</h3>
<p class=\"gameDesc\">".$row["Description"]."</p>";
if ($row["Price"] == 0) {
echo "<p class=\"gamePrice\">FREE</p>";
} else {
echo "<p class=\"gamePrice\">£".$row["Price"]."</p>";
echo" </div>
} else {
echo "0 results";


I can see the values in my address but nothing happens. The query works if I just include in php and make the user refresh every time.

UPDATE: changed both getElementByIds to have .value on the end

Answer Source

Change your button from input type="submit" to input type="button"

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download