Refresh table after ajax POST based on search criteria - javascript

All,
I have a modal that contains a table with results from a PHP query using PHP include, the problem is as the modal is loaded when the page if first opened, I appear to be unable to use an AJAX post later on to refresh the table based on a textbox variable.
Here is my code
HTML
<div class="modal-content">
<div class="modal-header">
<span class="close">x</span>
</div>
<div class="modal-body">
<div id="divSearchResultsTable">
<table class="tblSearchResults" id="tblSearchResults">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Home</th>
<th>Mobile</th>
<th>City</th>
<th>Country</th>
<th>Company</th>
</tr>
</thead>
<tbody>
<?php
include("sql_search.php");
?>
<tbody>
</table>
</div>
<div id="divSearchResultsButtons">
<input type="button" class="btnOpen" id="btnOpen" name="btnOpen" value="Open" disabled="true"/>
&nbsp
<input type="button" class="btnClose" id="btnClose" name="btnClose" value="Close"/>
</div>
</div>
</div>
JavaScript
$(function(){
$('#btnSearch').click(function(e){
var modal = document.getElementById('modal');
var value = $("#txtSearch").val();
$.ajax({
type : "POST",
url : "sql_search.php",
data : {value:value},
success : function(output) {
alert(output);
modal.style.display = 'block';
modal.focus();
}
});
});
});
PHP (sql_search.php)
$value = (isset($_POST['value']) ? $_POST['value'] : null);
if ($value == null){
$sql = "SELECT * FROM helpdesk";
}
else{
$sql = "SELECT * FROM helpdesk WHERE ID = $value";
}
$result = mysqli_query( $conn, $sql);
while( $row = mysqli_fetch_array($result))
{
echo '<tr>';
echo '<td>'.$row['ID'].'</td>' . '<td>'.date("d/m/Y g:i:s A", strtotime($row['DateCreated'])).'</td>' . '<td>'.$row['Priority'].'</td>' . '<td>'.$row['Company'].'</td>' . '<td>'.$row['Name'].'</td>' . '<td>'.$row['Subject'].'</td>' . '<td>'.$row['Name'].'</td>';
echo '</tr>';
}
The result I am getting is every database item returned. I've used alert(output) in my AJAX success to confirm the varible is actually being passed, so I think I now just need to work out how to get the table to update.
Any advice?
Thanks

Don't include your PHP file in html, but assign an id to the element where you'd like to have its output. Then in Javacsript, populate the content with the data returned by AJAX call.
<div class="modal-content">
<div class="modal-header">
<span class="close">x</span>
</div>
<div class="modal-body">
<div id="divSearchResultsTable">
<table class="tblSearchResults" id="tblSearchResults">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Home</th>
<th>Mobile</th>
<th>City</th>
<th>Country</th>
<th>Company</th>
</tr>
</thead>
<tbody id="modalContent">
<!-- note, no content and tbody has an ID -->
<tbody>
</table>
</div>
<div id="divSearchResultsButtons">
<input type="button" class="btnOpen" id="btnOpen" name="btnOpen" value="Open" disabled="true"/>
&nbsp
<input type="button" class="btnClose" id="btnClose" name="btnClose" value="Close"/>
</div>
</div>
</div>
And the javascript code:
$(function(){
$('#btnSearch').click(function(e){
var modal = document.getElementById('modal');
var value = $("#txtSearch").val();
$.ajax({
type : "POST",
url : "sql_search.php",
data : {value:value},
success : function(output) {
alert(output);
$('#modalContent').html(output); // <------
modal.style.display = 'block';
modal.focus();
}
});
});
});
BTW, your PHP code is unsafe as it uses its parameter directly in SQL query without validation or type casting (SQL injection) and outputs data from database without escaping html (stored HTML/Javascript injection). Consider using PDO with parameters - http://php.net/manual/en/pdostatement.bindparam.php and wrap database output values into htmlspecialchars() call

Related

How to update the database using a checkbox in a table column?

I am new to PHP and just began to learn JS as it is required at this phase of the project. I have a database named- asms
table named - filtersms
column named - filter_op . In this column of the table I have a checkbox for each row and my requirement is to enter 'yes' to the filter_op column once I check the checkbox and remains 'no' if not checked. I tried to do this using PHP itself but happens to be impossible to update the table on the click of the checkbox. As I am a beginner to JS can you please help me to get through this.
This is how filtersms table looks like,
|id |vendor |alarm_name |filter_op|
|1 |HUAWEI | communication fault |no |
|2 |HUAWEI | STP link fault |no |
|3 |ZTE | Battery discharge |no |
|4 |ZTE | AC power off |no |
Following is the PHP code I written so far to add a checkbox to each row and display the table.
<!-- Begin Page Content -->
<div class="container-fluid">
<!-- Page Heading -->
<h1 class="h2 mb-2 text-gray-800">Filter SMS</h1>
<!-- DataTales Example -->
<div class="card shadow mb-4">
<div class="card-header py-3">
<h4 class="m-0 font-weight-bold text-primary">Filtered SMS Summary</h4>
</div>
<div class="card-body">
<?php
//Table select query for database
require('include/connection.php');
$query1="SELECT* FROM filtersms ";
$result_set=mysqli_query($connection,$query1);
// require('include/filtercheck.php');
?>
<div class="table-responsive">
<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th>Vendor</th>
<th>Alarm</th>
<th>Filter Option</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Vendor</th>
<th>Alarm</th>
<th>Filter Option</th>
</tr>
</tfoot>
<tbody>
<?php
while($row=mysqli_fetch_assoc($result_set)) {
?>
<tr>
<td><?php echo $row["vendor"]; ?></td>
<td><?php echo $row["alarm_name"]; ?></td>
<td>
<form action="include/filtercheck.php" method="POST">
<div class="form-check">
<input type="checkbox" class="form-check-input" value="yes" name="filter_check" id="filter_check"/>
<label class="form-check-label" for="filter_check">Filter Alarm</label>
</div>
</form>
</td>
</tr>
<?php
}
?>
You can use jQuery.post() for it.
For each row, use:
<tr>
<td><?php echo $row["vendor"]; ?></td>
<td><?php echo $row["alarm_name"]; ?></td>
<td>
<input type="checkbox" value="2" class="js-checkbox-filter" <?php echo ($row["filter_op"] == "yes" ? "checked" : NULL) ?> />
</td>
</tr>
These checkbox are now identified by the js-checkbox-filter class, and you can use it to bind a jQuery.change() event handler on it.
var checks = $(".js-checkbox-filter")
checks.change(function() {
$.post("filtercheck.php", {
id: this.value,
filtered: this.checked ? "yes" : "no"
})
})
You'll have to change your filtercheck.php file too. It must receive an id and filtered ("yes"/"no") parameters through $_POST variable. Use them to update your database table.
You can try something like this if I understand your question correctly. That uses jQuery so you need to include the CDN script. That basically submits data via AJAX indicating the new filter options for the row checked or unchecked. It does that my posting an array as filter_op_post having index 0 = to true or false and index 1 equal to the id of the row in the database. You can process that in the filtercheck.php file, although I included a little snippet. Let me know if that works for you.
That AJAX response is in "data", so you can return whatever you want and process that as needed.
POST:
filter_op_post[] […]
0 true
1 2
RESPONSE:
["true","2"] e.g.
index.php page:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous">
</script>
<!-- Begin Page Content -->
<div class="container-fluid">
<!-- Page Heading -->
<h1 class="h2 mb-2 text-gray-800">
Filter SMS
</h1>
<!-- DataTales Example -->
<div class="card shadow mb-4">
<div class="card-header py-3">
<h4 class="m-0 font-weight-bold text-primary">
Filtered SMS Summary
</h4>
</div>
<div class="card-body">
<?php
$Config = array(
'DB_TYPE' => 'mysql',
'DB_HOST' => '127.0.0.1',
'DB_NAME' => 'alarmfilter',
'DB_USER' => 'root',
'DB_PASS' => 'root',
'DB_PORT' => '3306',
'DB_CHARSET' => 'utf8'
);
$options = array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ, PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING, PDO::ATTR_EMULATE_PREPARES => true );
try {
$database = new PDO($Config['DB_TYPE'] . ':host=' . $Config['DB_HOST'] . ';dbname=' . $Config['DB_NAME'] . ';port=' . $Config['DB_PORT'] . ';charset=' . $Config['DB_CHARSET'], $Config['DB_USER'], $Config['DB_PASS'], $options);
}
catch (PDOException $e) {
// Echo custom message. Echo error code gives you some info.
echo 'Database connection can not be estabilished. Please try again later.' . '<br>';
echo 'Error code: ' . $e->getCode();
// Stop application :(
// No connection, reached limit connections etc. so no point to keep it running
exit;
}
$query="SELECT* FROM filtersms ";
$parameters = [];
$stmt = $database->prepare($query);
$stmt->execute($parameters);
$result_set = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<div class="table-responsive">
<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th>Vendor</th>
<th>Alarm</th>
<th>Filter Option</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Vendor</th>
<th>Alarm</th>
<th>Filter Option</th>
</tr>
</tfoot>
<tbody>
<?php
foreach ($result_set as $row) {
?>
<tr>
<td><?php echo $row["vendor"]; ?>
</td>
<td><?php echo $row["alarm_name"]; ?>
</td>
<td>
<form>
<div class="form-check">
<?php $checked = ($row["filter_op"] == "true")?"checked":""; ?>
<input
<?php echo $checked; ?>
type="checkbox" class="form-check-input filter_check" id ="filter_op_id
<?php echo $row["id"]; ?>
"/>
<input type="hidden" name="filter_op_post[]" value="<?php echo $row[" filter_op"]; ?>
"/>
<input type="hidden" name="filter_op_post[]" value="<?php echo $row[" id"]; ?>
"/> <label class="form-check-label" for="filter_check">Filter Alarm</label>
</div>
</form>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
<style> table, table tr, table td {
border:black 1px solid;
border-collapse: collapse;
</style>
<script>
$(".filter_check").on("click", function(e) {
$(this).next().val($(this).prop("checked"));
formdata = $(this).closest("form").serialize();
$.ajax({
type: "POST",
url: 'include/filtercheck.php',
dataType: "json",
data: formdata,
beforeSend: function(e) {
// $("#spinner").css("display", "block");
},
})
.done(function(data, textStatus, jqXHR) {
alert(data);
})
.fail(function( jqXHR, textStatus, errorThrown) {
})
.always(function(jqXHR, textStatus) {
$("#spinner").css("display", "none");
});
});
</script>
include/filtercheck.php page:
<?php
$rowid = $_POST['filter_op_post'][1];
$filter_op_value = $_POST['filter_op_post'][0];
echo json_encode($_POST['filter_op_post']);
?>
You could use a form with a submit button.
<form method="POST">
<input type="checkbox" class="form-check-input" value="true" name="filter_check" id="filter_check"/>
<label class="form-check-label" for="filter_check">
<button type="submit" name"submit" value="Submit">Submit</button>
</form>
With this you could update the database using the Post method
if(isset($_POST['submit']))
{
/* update database here
/* your value of the checkbox is &_POST['filter_check']
}

Pass values using JSON via Ajax Call

I am beginner on JSON. In my web application I am trying convert the table values into JSON and pass to another page using ajax call.
Below is my ajax query which I tried to convert the table values and pass to prescription.php page to save the records. There are two different separate java script variables which need to sent to the above page.
<script>
$(document).ready(function () {
$(document).on('click', '#submit', function () {
var getapt = $('#getapt').val();
var getpid = $('#getpid').val();
var ids={
'getapt': getapt,
'getpid': getpid,
}
var modess = $('#rows tr').map(function() {
let $tr = $(this);
return [{
"medname": $(this).find('.med_name').val(),
"morning": $(this).find('.morning').val(),
"noon": $(this).find('.noon').val(),
"night": $(this).find('.night').val(),
}]
console.log(modess);
});
var ids = JSON.stringify(ids);
var medical = JSON.stringify(modess);
$.ajax({
url: "adminquery/prescription.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data:{
index1: medical,
index2: ids
},
dataType:'json',
cache: false,
contentType: false,
processData: false,
async: false,
//contentType: "application/json; charset=utf-8",
})
});
});
</script>
Here is my prescription.php page
<?php
session_start();
require_once "../auth/dbconnection.php";
// if (isset(json_decode($_POST["data"])) {
$medical = json_decode($_POST["data"]);
if($stmt = mysqli_prepare($conn,"INSERT INTO prescription (apt_id,user_id,p_id, med_records,date) VALUES (?, ?, ?, ?, ?)")){
$user_id = $_SESSION['user_id'];
mysqli_stmt_bind_param($stmt, "sssss", $user_id);
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not prepare query: $sql. " . mysqli_error($conn);
}
// }else{
// echo "now records";
// }
mysqli_stmt_close($stmt);
?>
Here is my HTML codes.
<form method="post" id="prescriptionn" enctype="multipart/form-data">
<div class="table-responsive">
<table class="table table-bordered mb-0" id="medical">
<thead>
<tr>
<th>Medicine Name</th>
<th>Morning</th>
<th>Noon</th>
<th>Night</th>
<th> <button type="button" name="add" id="add" class="btn btn-success btn-xs">
+ </button> </th>
</tr>
</thead>
<tbody id="rows">
</tbody>
</table>
<br><br>
<div align="center">
<input type="hidden" value="<?php echo $row['apt_id'] ?>" id="getapt"
name="getapt" class="btn btn-primary">
<input type="hidden" value="<?php echo $row['p_id'] ?>" id="getpid" name="getpid" class="btn btn-primary">
<input type="button" name="submit" id="submit" class="btn btn-primary" value="Enter Prescription">
</div>
</div>
</form>
But nothing happen when I submit the button. Please give me some suggestions to improve my code may highly appreciated.
Following Method show how to send HTML table data using jQuery Ajax and save in Database. Hope this will help.
function storeTblValuesSpecial(x)
{
var TableData = new Array();
$('#'+x+''+' tr').each(function(row, tr){
TableData[row]={
"columOne" :$(tr).find('td:eq(1)').text()
, "columTwo" : $(tr).find('td:eq(2)').text()
, "columThree" : $(tr).find('td:eq(3)').text()
}
});
TableData.shift(); // first row will be empty - so remove
return TableData;
}
function storeTblValuesAjax(y) {
var TableData;
TableData = JSON.stringify(storeTblValuesSpecial(y));
$.ajax({
type: "POST",
url: '../yourFile.php',
data: {
"pTableData" : TableData
},
success: function(msg){
alert('Success');
}
});
}
<table id="table1" class="table table-dark" border="1">
<thead>
<tr>
<th scope="col">columOne</th>
<th scope="col">columTwo</th>
<th scope="col">columThree</th>
</tr>
</thead>
<tbody>
<tr>
</tr>
</tbody>
</table>
<button type="button" class="btn-danger" id = "delete" onclick="storeTblValuesAjax('table1')" >Save Table</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
From PHP File once the Post Request Sent through Ajax Call
<?php
session_start();
// Unescape the string values in the JSON array
$tableData = stripcslashes($_POST['pTableData']);
// Decode the JSON array
$records = json_decode($tableData,TRUE);
$sizeOfArray = sizeof($records);
for($test = 1; $test < $sizeOfArray; $test++)
{
$columOne= str_replace(",","",$records[$test]['columOne']);
$columTwo= str_replace(",","",$records[$test]['columTwo']);
$columThree= str_replace(",","",$records[$test]['columThree']);
/* From Here a general SQL Insert query , pass $columOne , $columTwo , $columThree as the insert values, the loop will continue until the entire table is saved */
}

JavaScript Remove <tr> Table Row Dynamically

I'm trying to remove row from my dynamic table. I've success to .append new row from JavaScript.
JavaScript
$(document).ready(function() {
// table #pos add-row
$(".add-row").keypress(function(e) {
if (e.which == 13) {
var barcode = $("#barcode").val();
$.ajax({
type: "post",
url: "production/ajax/load.php",
dataType: "json",
data: {
barcode: $("#barcode").val()
},
success: function(data) {
$("#pos tbody").append(data['content']);
}
});
}
});
// Find and remove selected table rows
$(".delete-row").click(function(){
alert('Success');
$("#pos tbody tr").remove();
});
})
load.php
<?php
if (isset($_POST['barcode'])) {
require '../controller/connection/connection-management.php';
$barcode = $_POST['barcode'];
$status = false;
$sql = "SELECT code, title, wri_name, pub_name, year, main_category.main_category, category.category, call_number, pusat_penerbit, mrican, paingan, selling_price, discount FROM product, writer, publisher, main_category, category WHERE product.writer = writer.writer AND product.publisher = publisher.publisher AND product.main_category = main_category.main_category AND product.category = category.category AND code = '{$barcode}' ORDER BY title";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) == 1) {
while($row = mysqli_fetch_assoc($result)) {
$barcode = $row['code'];
$title = $row['title'];
$sellingPrice = number_format($row['selling_price'], 0, ',', '.');
$quantity = 1;
$discount = $row['discount'];
$total = number_format((($row['selling_price'] - ($row['selling_price'] * ($discount / 100))) * $quantity), 0, ',', '.');
$append = "<tr class='pointer'>
<td align='right'><a href='javascript:;' class='delete-row'><i class='fa fa-trash'></i></a></td>
<td><small>{$barcode}</small></td>
<td><div style='text-align: justify'><strong>{$title}</strong></div></td>
<td align='right'>{$sellingPrice}</td>
<td align='center'><input id='quantity' type='text' class='form-control' style='text-align:center' value='1'></td>
<td align='center'><input type='text' class='form-control' style='text-align:center' value='{$discount}'></div></td>
<td align='right'>{$total}</td></td>
</tr>";
}
$status = true;
}
$data = array(
"status" => $status,
"content" => $append
);
echo json_encode($data);
}
?>
pos.php it's html table
<div class="x_title">
<div class="input-group">
<span class="input-group-btn">
<button type="button" class="delete-row btn btn-primary"><i class="fa fa-pencil-square-o"></i></button>
</span>
<input name="barcode" id="barcode" type="text" class="add-row form-control" placeholder="Enter item name or scan barcode">
<div class="input-group-btn">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">Receive</button>
<ul class="dropdown-menu dropdown-menu-right" role="menu">
<li>Receive</li>
<li>Return</li>
<li>Purchase Order</li>
<li>Transfer</li>
<li>Store Account Payment</li>
</ul>
</div>
</div>
</div>
<div class="x_content">
<div class="table-responsive">
<table name="pos" id="pos" class="table table-striped jambo_table bulk_action">
<thead>
<tr class="headings">
<th style="text-align:center" class="column-title col-sm-7" colspan="3">Item Name </th>
<th style="text-align:right" class="column-title col-sm-1">Cost </th>
<th style="text-align:center" class="column-title col-sm-2">Qty. </th>
<th style="text-align:center" class="column-title col-sm-1">Disc % </th>
<th class="column-title col-sm-1" style="text-align:right">Total </th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
So when I add new row in the table, everything works fine like this picture:
But when I click trash icon with class='delete-row', that's is not working. So I think, when I append data to table tbody it's not read class or id from the new row.
Please someone help. I can't find any similar questions like mine. I just want to know, how to remove table row when I click trash icon from JavaScript.
You have two issues here (which is why I have not voted to close as a duplicate). Firstly you need to use a delegated event handler on the .delete-row element as it is appended to the DOM after load. Your current code does nothing as you attempt to attach the event handler before the element exists.
Secondly, you need to use DOM traversal to remove only the parent tr of the clicked button. At the moment your code would remove all rows. Try this:
$('#pos').on('click', '.delete-row', function() {
$(this).closest('tr').remove();
});
Did you tried delegate?
$(document).delegate('.delete-row', 'click', function(){
//your remove code here
});
You can also use on (for jquery versions 1.7.1+)
$(document).on('click', '.delete-row', function(){
//your remove code here
});

Need idea to use variable JS outside and use button to send data

This script save the id of the row I clicked. But now I would like to do :
"If I click on buttonmodif then change url and send the variable number (which is the id of the row) into the url (and the next page) . I'm not sure how to do it.
I would like to save the variable number outside the script and when I click on buttonmodif I send my variable to another url.
Thank you for your answer!
HTML FILE :
<div id="page-wrapper" style=" padding-left: 20px">
<form method="post" name="employes1" action="employes.php">
<div class="container-fluid">
<div class="row">
<div class=" text-center">
<button type="button"
class="btn btn-default"><?php echo '<a href="employesajout.php" > Ajouter un employé </a>'; ?></button>
<button type="submit" name="buttonmodif" id="modifon"> Mofidier informations</button>
<button type="submit" class="btn btn-default">Supprimer employé</button>
<button type="button" class="btn btn-default">Créer un contrat de travail</button>
</div>
</div>
<div class="row table-responsive">
<table class="table table-bordered table-hover" id="MyTable">
<thead class="-inverse">
<?php
$rep = $bdd->prepare('SELECT * from employee');
$rep->execute();
$resultat = $rep->fetchAll();
?>
<tr>
<th>#</th>
<th>Nom</th>
<th>Prénom</th>
<th>Résidence</th>
<th>NAS</th>
<th>Date d'entré</th>
<th>Heure /semaine</th>
<th>Salaire brute</th>
<th>Salaire net</th>
<th>Vacance (s)</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<?php foreach ($resultat as $row) {
echo "
<tr class ='clickable-row'>
<td>$row[0]</td>
<td>$row[1]</td>
<td>$row[2]</td>
<td>$row[3]</td>
<td>$row[4]</td>
<td>$row[5]</td>
<td>$row[6]</td>
<td>$row[7]</td>
<td>$row[8]</td>
<td>$row[9]</td>
<td>$row[10]</td>
</tr>";
};
?>
<script>
$(document).ready(function ($) {
$(".clickable-row").click(function () {
var number = parseInt($(this).closest('tr').children().eq(0).text());
console.log(number);
});
// active click hilight
$('td').click(function () {
$('tr').removeClass('active');
$(this).parent().addClass('active');
});
});
</script>
</tbody>
</table>
</div>
</div>
</form>
</div>
Declare the variable outside the click function. Then bind a click handler on the buttonmodif button that uses the variable. You can add a type="hidden" input to the form, and put the value there.
$(document.ready(function() {
var number;
$(".clickable-row").click(function() {
number = parseInt($(this).closest('tr').children().eq(0).text());
console.log(number);
});
$("#modifon").click(function() {
$("#hiddenfield").val(number);
});
});

Making search function ajax

Hello I am trying to make an ajax search function in my project.
The app loads all Clients data into table on the webpage first.
and If something is typed on the searchbar,
I want searched data to be shown instead of all clients data.
I tried various ways but none of them worked out as I intended to.
Firstly I added function to check if it has any value within searchbar and if it has any value it will try to find within database and fetch data. but if it hasn't got any value it will show all client data by default.
Here is my example script code
// READ records
function readRecords() {
var searchbar = $("#search").val();
if (searchbar.val() > 0) {
$.post("ajax/search.php", {
searchbar: searchbar
}, function (data, status) {
$(".records_content").html(data);
});
} else {
$.get("ajax/readRecords.php", {}, function (data, status) {
$(".records_content").html(data);
});
}
}
Code snippet of index
<!-- Content Section -->
<div class="container">
<div class="row">
<div class="col-md-12">
<h1>Client List</h1>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="pull-xs-right">
<button class="btn btn-success" data-toggle="modal" data-target="#add_new_record_modal">Add New Client</button>
</div>
<div class="col-sm-3">
<form class="form-inline global-search" role="form" method="POST" onsubmit="readRecords()">
<div class="form-group">
<input type="text" class="form-control" id="search" placeholder="Search">
<button type="submit" id="search" class="btn btn-primary">Search</button>
</div>
</form>
</div>
</div>
</div>
<div class="row">
<div class ="col-lg-12">
<!--Where the results will be printed-->
<div class="records_content"></div>
</div>
</div>
</div>
search.php
<?php
if(isset($_POST['search']) && isset($_POST['search']) != "") {
// include Database connection file
include("SQLFunctions.php");
// Design initial table header
$data = '<table class="table table-bordered">
<tr>
<th>No.</th>
<th>Surname</th>
<th>Name</th>
<th>Address</th>
<th>Telephone</th>
<th>Inspection</th>
<th>Model</th>
<th>Serial Number</th>
<th>Notes</th>
<th>A/S Request</th>
<th>Update</th>
<th>Delete</th>
</tr>';
$search = $_POST['search'];
$searchquery = "SELECT Surname
,Name
,Address
,Telephone
,DATE_FORMAT(PurchaseDate, '%Y-%m-%d')
,Model
,SerialNumber
,Notes
FROM Clients
WHERE Surname LIKE '%".$search."%' OR Name LIKE '%".$search."%' OR Model Like '%".$search."%'";
$link = connectDB();
;
// if query results contains rows then fetch those rows
if($result = mysqli_query($link, $searchquery))
{
$number = 1;
while($row = mysqli_fetch_assoc($result))
{
$data .= '<tr>
<td>'.$number.'</td>
<td>'.$row['Surname'].'</td>
<td>'.$row['Name'].'</td>
<td>'.$row['Address'].'</td>
<td>'.$row['Telephone'].'</td>
<td>'.$row['PurchaseDate'].'</td>
<td>'.$row['Model'].'</td>
<td>'.$row['SerialNumber'].'</td>
<td>'.$row['Notes'].'</td>
<td>
<button onclick="Request('.$row['id'].')" class="btn btn-primary">A/S Request</button>
</td>
<td>
<button onclick="GetUserDetails('.$row['id'].')" class="btn btn-warning">Update</button>
</td>
<td>
<button onclick="DeleteUser('.$row['id'].')" class="btn btn-danger">Delete</button>
</td>
</tr>';
$number++;
}
}
else
{
// records now found
$data .= '<tr><td colspan="6">Records not found!</td></tr>';
}
$data .= '</table>';
echo $data;
}
?>
When I run this project, everything work properly but When I enter any value into searchbar it gives same all results of clients.
I am trying to figure out which is the best way to make this function functioning. Any tips would be appreciated thank you in advance
Prevent the default submit event
onsubmit="readRecords(this)"
function readRecords(e) {
e.preventDefault();
var searchbar = $("#search").val();
if (searchbar.val() > 0) {
$.post("ajax/search.php", {
searchbar: searchbar
}, function (data, status) {
$(".records_content").html(data);
});
} else {
$.get("ajax/readRecords.php", {}, function (data, status) {
$(".records_content").html(data);
});
}
}
use event.preventDefault() method of jquery before calling the ajax request.
If this method is called, the default action of the event will not be triggered.

Categories