javascript - Display and filter sql table without reloading page with PHP
one text
I have an sql table which is displayed in PHP and can also be filtered with a dropdown. The only problem is when I filter the table, the form reloads the page so some other functions on the page reset. So I need to filter the table without the form reloading the page so everything else stays the same and works.
I have tried "onSubmit="return false;", but that stops the whole form working.
Is there any other ways to stop it reloading, preferably with jquery or ajax.
Thanks
<?php
class DBController {
private $host = "hostname";
private $user = "username";
private $password = "password";
private $database = "databasename";
private $conn;
function __construct() {
$this->conn = $this->connectDB();
}
function connectDB() {
$conn = mysqli_connect($this->host,$this->user,$this->password,$this->database);
return $conn;
}
function runQuery($query) {
$result = mysqli_query($this->conn,$query);
while($row=mysqli_fetch_assoc($result)) {
$resultset[] = $row;
}
if(!empty($resultset))
return $resultset;
}
}
$db_handle = new DBController();
$Muscle_NameResult = $db_handle->runQuery("SELECT DISTINCT Muscle_Name FROM gym_exercises ORDER BY Muscle_Name ASC");
?>
<form method="POST" action="add-exercise.php" onSubmit="return false;">
<div id="demo-grid">
<div class="search-box">
<select id="Place" name="Muscle_Name[]" multiple="multiple">
<option value="0" selected="selected">Select Muscle_Name</option>
<?php
if (! empty($Muscle_NameResult)) {
foreach ($Muscle_NameResult as $key => $value) {
echo '<option value="' . $Muscle_NameResult[$key]['Muscle_Name'] . '">' . $Muscle_NameResult[$key]['Muscle_Name'] . '</option>';
}
}
?>
</select><br> <br>
<input id="Filter" type="submit" />
</div>
<?php
if (! empty($_POST['Muscle_Name'])) {
?>
<table cellpadding="10" cellspacing="1">
<thead>
<tr>
<th><strong>Exercise</strong></th>
<th><strong>Muscle</strong></th>
<th><strong>Push/Pull</strong></th>
</tr>
</thead>
<tbody>
<?php
$query = "SELECT * from gym_exercises";
$i = 0;
$selectedOptionCount = count($_POST['Muscle_Name']);
$selectedOption = "";
while ($i < $selectedOptionCount) {
$selectedOption = $selectedOption . "'" . $_POST['Muscle_Name'][$i] . "'";
if ($i < $selectedOptionCount - 1) {
$selectedOption = $selectedOption . ", ";
}
$i ++;
}
$query = $query . " WHERE Muscle_Name in (" . $selectedOption . ")";
$result = $db_handle->runQuery($query);
}
if (! empty($result)) {
foreach ($result as $key => $value) {
?>
<tr>
<td><div class="col" id="user_data_1"><button onclick="addExerciseName()"><?php echo $result[$key]['Exercise_Name']; ?></button></div></td>
<td><div class="col" id="user_data_2"><?php echo $result[$key]['Muscle_Name']; ?> </div></td>
<td><div class="col" id="user_data_3"><?php echo $result[$key]['PPS']; ?> </div></td>
</tr>
<?php
}
?>
</tbody>
</table>
<?php
}
?>
</div>
</form>
Source