Making search function ajax - javascript

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.

Related

live search opetion in codeigniter with ajax

I am new to codeIgniter. want to learn this. I am facing problem. data is not populated in search page.
in model
function fetch_data($query)
{
$this->db->select('*');
$this->db->from('casedata');
if($query!='')
{
$this->db->like('status',$query);
}
$this->db->order_by('SrNo','DESC');
return $this->db->get();
}
in controller the fetch function not getting data from database
function fetch()
{
$output='';
$query='';
$this->load->model('crud_model');
if ($this->input->post('query'));
{
$query= $this->input->post('query');
}
$data=$this->Crud_model->fetch_data($query);
$output .='<div class="table-responsive">
<table class="table table_bordered table-striped
<tr>
<th>SrNo.</th>
<th>Tile</th>
<th>File No.</th>
<th>Division</th>
<th>Section</th>
<th>LDH</th>
<th>NDH</th>
<th>PDH</th>
<th>STATUS</th>
</tr>';
if($data->num_rows()>0)
{
foreach($data->result() as $row)
{
$output.='<tr> <td>'.$row->SrNo.'</td>
$output.='<tr> <td>'.$row->title.'</td>
<td>'.$row->fileno.'</td>
<td>'.$row->division.'</td>
<td>'.$row->section.'</td>
<td>'.$row->ldh.'</td>
<td>'.$row->ndh.'</td>
<td>'.$row->pdh.'</td>
<td>'.$row->status.'</td></tr>';
}
}
else{
$output.='<tr> <td colspan="5">No Data Found</td></tr> ';
}
$output.='</table>';
echo $output;
}
in view
<html>
<body>
<div class="row">
<div class="col-md-12">
<div class="panel panel-primary" data-collapsed="0">
<div class="panel-heading">
<div class="panel-title" >
<i class="entypo-plus-circled"></i>
<?php echo get_phrase('Search Data');?>
</div>
</div>
<div class="panel-body">
<?php echo form_open(base_url() . 'index.php?
admin/student/create/' , array('class' => 'form-horizontal form-groups-
bordered validate', 'enctype' => 'multipart/form-data'));?>
<div class="form-group">
<input type="text" name="search_text" id="search_text"
placeholder="Search by Customer Detsils" class="form-control"/>
<div id="result">
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function()
{
load_data();
function load_data(query)
{
$.ajax({
url:"<?php echo base_url();?>index.php?
admin/fetch",method:"POST",
data:{query:query},
success:function(data){
$('#result').html(data);
}
})
}
$('#search_text').keyup(function(){
var search=(this).val();
if (search!='')
{
load_data(search);
}
else
{ load_data();
}
} );
});
</script>
Data is not populated in table. How to get output from this?
You need to loop throught the $data variable. please change the 'if' and 'foreach' as below code.
if(is_array($data) && count($data)>0)
{
foreach($data as $row)
{
still if it not working try var_dump($data) and check whether results are coming or not.

Unable to load data on dashboard via ajax

I have a partial view named SIM Balance in mine dashboard. This view should show the number of sims issued to a user date wise.
I have set up the controller
public function actionSimbalance()
{
$sql = "SELECT user.`name` AS issued_to, COUNT(`sims`.`id`) AS sims_issued, sims.`operator_name` AS operator_name,
CASE
WHEN sims.`status` = 'Production Stored SIM' THEN
CAST(`sim_issueance_transaction`.`issued_at` AS DATE)
WHEN sims.`status` = 'Testing Stored SIM' THEN
CAST(`sim_issueance_transaction`.`issued_at` AS DATE)
WHEN sims.`operator_name` = 'Zong' THEN
CAST(`sim_issueance_transaction`.`issued_at` AS DATE)
WHEN sims.`operator_name` = 'Mobilink' THEN
CAST(`sim_issueance_transaction`.`issued_at` AS DATE)
ELSE CAST(`sims`.`created_at` AS DATE) END AS issued_date
FROM `sims`
INNER JOIN `sim_issueance_transaction` ON (`sims`.`id` =
`sim_issueance_transaction`.`sim_id`)
INNER JOIN `user` ON (`sims`.`issued_to` = `user`.`id`)
WHERE sims.`status` IN ('Testing Stored SIM','Production Stored SIM')
GROUP BY user.`name`, sims.`status`, issued_date, sims.`operator_name`";
$rows = Yii::$app->db->createCommand($sql)->queryAll();
$output = [];
$grandtotal = 0;
foreach ($rows as $row) {
$std = new \stdClass();
$std->count = $row['sims_issued'];
$std->issued_to = $row['issued_to'];
$std->operator = $row['operator_name'];
$std->issued_date = $row['issued_date'];
$grandtotal += $std->count;
$output[]= $std;
}
return $this->renderPartial('sim_progress', ['model' => $output, 'grandtotal' => $grandtotal]);
}
The partial view sim_progress is below
<?php foreach ($model as $row){?>
<tr>
<td><?=$row->issued_to?></td>
<td><?=$row->count?></td>
<td><?=$row->operator?></td>
<td><?= $row->issued_date ?></td>
</tr>
<?php } ?>
<tr>
<td><strong>Grand Total</strong></td>
<td>
<strong><?= $grandtotal ?></strong>
</td>
<td></td>
</tr>
Then there is an HTML sim-balance I have designed
<div class="box box-info">
<div id="af8a8d88334">
<div class="print-header print-only">
<center><img style="width: 100px" src="<?=
\yii\helpers\Url::to('#web/images/logo.png', true); ?>"/>
</center>
<br/>
<hr/>
</div>
<div class="box-header with-border">
<h3 class="box-title">SIM Balance</h3>
</div>
<div class="box-body">
<div class="table-responsive">
<table class="table no-margin">
<thead>
<tr>
<th>Issued To</th>
<th>Sims Issued</th>
<th>Operator Name</th>
<th>Issued At</th>
</tr>
</thead>
<tbody id="dashboard-sim-balance">
</tbody>
</table>
</div>
</div>
</div>
<div class="box-footer clearfix">
<a href="javascript:void(0)" onclick="$('#af8a8d88334').printThis();"
class="btn btn-sm btn-default btn-flat pull-right">Print</a>
</div>
Then in my main site index view, I am calling it like below
.
.
.
<?php if (!Yii::$app->user->isGuest && in_array(Yii::$app->user->identity->user_role,[1,6])) {
echo $this->render('dashboard/sim-balance');
} ?>
.
.
.
.
$url_sim_balance = Url::toRoute('/dashboard/simbalance');
.
.
.
.
In my JS I am creating an ajax function which should show the details.
$script = <<< JS
$(document).ready(function () {
.
.
.
.
loadSimBalance();
.
.
.
});
function loadSimBalance() {
$('#dashboard-sim-balance').html('');
$.ajax({
url: '$url_sim_balance',
data: data.val(), // also tried $('#dashboard-sim-balance').val()
success:function(data) {
$('#dashboard-sim-balance').html(data);
},
error: function() {
}
});
}
JS;
$this->registerJs($script);
But when I run my project I cannot see the details but an empty table like below
How can I set my ajax call to view the details.
Any help would be highly appreciated.
change
function loadSimBalance() {
$('#dashboard-sim-balance').html('');
$.ajax({
url: '$url_sim_balance',
data: data.val(), // also tried $('#dashboard-sim-balance').val()
success:function(data) {
$('#dashboard-sim-balance').html(data);
},
error: function() {
}
});
}
To
function loadSimBalance() {
$('#dashboard-sim-balance').html('');
$.ajax({
url: '$url_sim_balance',
success:function(data) {
$('#dashboard-sim-balance').html(data);
},
error: function() {
}
});
}

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);
});
});

Refresh table after ajax POST based on search criteria

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

Categories