Laravel confirm delete in an alert in my view - javascript

This should be a simple task I am just not fully grasping laravel yet.
I have my controllers view and models setup. I want to use my users.destroy route to delete my row in the db. But I want to do it a certain way. I want to have an alert show In my alert area on my page asking to confirm the deletion of a certain user. Im assuming I need to pass the user id in a session to an alert to confirm my delete on a delete button click.
Click 1 button to open an alert on the top of my page if I click confirm it calls user.destroy.
View:
<div class="container">
<div class="row justify-content-center">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h4>View All Users</h4>
#if(session()->get('success'))
<div class="alert alert-success">
{{ session()->get('success') }}
</div>
#endif
#if(session()->get('danger'))
<div class="alert alert-danger">
{{ session()->get('danger') }}
</div>
#endif
</div>
<div class="card-body">
<div class="text-center my-2">
New User
</div>
<div>
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Username</th>
<th colspan="2">Actions</th>
</tr>
</thead>
<tbody>
#foreach($users as $user)
<tr>
<th>{{$user->id}}</th>
<td>{{$user->name}}</td>
<td>{{$user->email}}</td>
<td>{{$user->username}}</td>
<td class="text-center">
Show
Edit
Delete
</td>
</tr>
#endforeach
</tbody>
</table>
Controller:
public function destroy($id)
{
User::find($id)->delete();
return redirect()->route('users.index')->with('success','User Deleted');
}
Route:
Route::resource('users', 'UserController');

Always try to use DELETE method for delete resource that is best way and practice
<div class="container">
<div class="row justify-content-center">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h4>View All Users</h4>
#if(session()->get('success'))
<div class="alert alert-success">
{{ session()->get('success') }}
</div>
#endif
#if(session()->get('danger'))
<div class="alert alert-danger">
{{ session()->get('danger') }}
</div>
#endif
</div>
<div class="card-body">
<div class="text-center my-2">
New User
</div>
<div>
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Username</th>
<th colspan="2">Actions</th>
</tr>
</thead>
<tbody>
#foreach($users as $user)
<tr>
<th>{{$user->id}}</th>
<td>{{$user->name}}</td>
<td>{{$user->email}}</td>
<td>{{$user->username}}</td>
<td class="text-center">
Show
Edit
<form method="POST" action="{{ route('users.delete', $user->id) }}">
#csrf // or hidden field
<input name="_method" type="hidden" value="DELETE">
<button type="submit" class="btn btn-xs btn-danger btn-flat show_confirm" data-toggle="tooltip" title='Delete'> <i class="fa fa-trash"> </i></button>
</form>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$('.show_confirm').click(function(e) {
if(!confirm('Are you sure you want to delete this?')) {
e.preventDefault();
}
});
</script>
If you are using Laravel collective HTML then you can replace that form tag

Its Just An Example i am considering your model as User.php
If You want icon just add the font awesome css
Open Your User.php Model and paste the below code
/**
* #function tableActionButtons
* #author Manojkiran <manojkiran10031998#gmail.com>
* #param string $fullUrl
* #param integer $id
* #param string $titleValue
* #param array $buttonActions
* #usage Generates the buttons
* #version 1.0
**/
/*
NOTE:
if you want to show tooltip you need the JQUERY JS and tooltip Javascript
if you are not well in JavaScript Just Use My Function toolTipScript()
|--------------------------------------------------------------------------
| Generates the buttons
|--------------------------------------------------------------------------
|Generates the buttons while displaying the table data in laravel
|when the project is bigger and if you are laravel expert you this.
|But if you are the learner just go with basic
|
|Basically It Will generate the buttons for show edit delete record with the default
|Route::resource('foo',FooController);
|
|//requirements
|
|//bootstrap --version (4.1.3)
|// <link rel="stylesheet"href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="" crossorigin="">
|//fontawesome --version (5.6.0(all))
|//<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.0/css/all.css" integrity="" crossorigin="">
|
|if you want to show tooltip you nee the jquery and tooltip you need these js and toottipscript javascript or use my function toolTipScript
|
|//jquery
|// <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
|//popper js
|// <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
|//bootstrap js
|// <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
|
|usage
|option1:
|tableActionButtons(url()->full(),$item->id,$item->name);
|this will generate all the buttons
|
|option2:
|tableActionButtons(url()->full(),$item->id,$item->name,['edit',delete]);
|this will generate edit and delete the buttons
|
|option3:
|tableActionButtons(url()->full(),$item->id,$item->name,['edit',delete,delete],'group');
|this will generate all the buttons with button grouping
|
|option4:
|tableActionButtons(url()->full(),$item->id,$item->name,['show','edit','delete'],'dropdown');
|this will generate all the buttons with button dropdown
|
*/
public static function tableActionButtons($fullUrl, $id, $titleValue, $buttonActions = ['show', 'edit', 'delete'], $buttonOptions = '', $encryptId = false)
{
$fullUrl = strtok($fullUrl, '?');
if ($encryptId) {
$id = Crypt::encrypt($id);
}
// dd(get_class_methods(HtmlString::class));
//Value of the post Method
$postMethod = 'POST';
//if the application is laravel then csrf is used
$token = csrf_token();
//NON laravel application
// if (function_exists('csrf_token'))
// {
// $token = csrf_token();
// }elseif (!function_exists('csrf_token'))
// //else if the mcrypt id is used if the function exits
// {
// if (function_exists('mcrypt_create_iv'))
// {
// // if the mcrypt_create_iv id is used if the function exits the set the token
// $token = bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));
// }
// else{
// // elseopenssl_random_pseudo_bytes is used if the function exits the set the token
// $token = bin2hex(openssl_random_pseudo_bytes(32));
// }
// }
//action button Value
//(url()->full()) will pass the current browser url to the function[only aplicable in laravel]
$urlWithId = $fullUrl . '/' . $id;
//Charset UsedByFrom
$charset = 'UTF-8';
// Start Delete Button Arguments
//title for delete functions
$deleteFunctionTitle = 'Delete';
//class name for the deletebutton
$deleteButtonClass = 'btn-delete btn btn-xs btn-danger';
//Icon for the delete Button
$deleteButtonIcon = 'fa fa-trash';
//text for the delete button
$deleteButtonText = 'Delete';
//dialog Which needs to be displayes while deleting the record
$deleteConfirmationDialog = 'Are You Sure you wnat to delete ' . $titleValue;
$deleteButtonTooltopPostion = 'top';
// End Delete Button Arguments
// Start Edit Button Arguments
//title for Edit functions
$editFunctionTitle = 'Edit';
$editButtonClass = 'btn-delete btn btn-xs btn-primary';
//Icon for the Edit Button
$editButtonIcon = 'fa fa-edit';
//text for the Edit button
$editButtonText = 'Edit';
$editButtonTooltopPostion = 'top';
// End Edit Button Arguments
// Start Show Button Arguments
//title for Edit functions
$showFunctionTitle = 'Show';
$showButtonClass = 'btn-delete btn btn-xs btn-primary';
//Icon for the Show Button
$showButtonIcon = 'fa fa-eye';
//text for the Show button
$showButtonText = 'Show';
$showButtonTooltopPostion = 'top';
// End Show Button Arguments
//Start Arguments for DropDown Buttons
$dropDownButtonName = 'Actions';
//End Arguments for DropDown Buttons
$showButton = '';
$showButton .= '
<a href="' . $fullUrl . '/' . $id . '"class="' . $showButtonClass . '"data-toggle="tooltip"data-placement="' . $showButtonTooltopPostion . '"title="' . $showFunctionTitle . '-' . $titleValue . '">
<i class="' . $showButtonIcon . '"></i> ' . $showButtonText . '
</a>
';
$editButton = '';
$editButton .= '
<a href="' . $urlWithId . '/edit' . '"class="' . $editButtonClass . '"data-toggle="tooltip"data-placement="' . $editButtonTooltopPostion . '" title="' . $editFunctionTitle . '-' . $titleValue . '">
<i class="' . $editButtonIcon . '"></i> ' . $editButtonText . '
</a>
';
$deleteButton = '';
$deleteButton .= '
<form id="form-delete-row' . $id . '" method="' . $postMethod . '" action="' . $urlWithId . '" accept-charset="' . $charset . '"style="display: inline" onSubmit="return confirm("' . $deleteConfirmationDialog . '")">
<input name="_method" type="hidden" value="DELETE">
<input name="_token" type="hidden" value="' . $token . '">
<input name="_id" type="hidden" value="' . $id . '">
<button type="submit"class="' . $deleteButtonClass . '"data-toggle="tooltip"data-placement="' . $deleteButtonTooltopPostion . '" title="' . $deleteFunctionTitle . '-' . $titleValue . '">
<i class="' . $deleteButtonIcon . '"></i>' . $deleteButtonText . '
</button>
</form>
';
// $deleteButton = "<span class='label label-success'>" ."Test" . "</span>";
$actionButtons = '';
foreach ($buttonActions as $buttonAction) {
if ($buttonAction == 'show') {
$actionButtons .= $showButton;
}
if ($buttonAction == 'edit') {
$actionButtons .= $editButton;
}
if ($buttonAction == 'delete') {
$actionButtons .= $deleteButton;
}
}
if (empty($buttonOptions)) {
return new HtmlString($actionButtons);
} elseif (!empty($buttonOptions)) {
if ($buttonOptions == 'group') {
$buttonGroup = '<div class="btn-group" role="group" aria-label="">
' . $actionButtons . '
</div>';
return new HtmlString($buttonGroup);
} elseif ($buttonOptions == 'dropdown') {
$dropDownButton =
'<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
' . $dropDownButtonName . '
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
' . $actionButtons . '
</div>
</div>
';
return new HtmlString($dropDownButton);
} else {
return 'only <code>group</code> and <code>dropdown</code> is Available ';
}
}
}
Now add this to User.php
use Illuminate\Support\HtmlString;
Now Open Your List index.blade.php and inside the for loop iteration add the below line
{{ App\User::tableActionButtons(url()->full(),$user->id,$user->name,['delete'],null,false) }}
If You want Multiple Buttons 4rt argument Accepts Array
{{ App\User::tableActionButtons(url()->full(),$user->id,$user->name,['show','edit,'delete],null,false) }}
If You face any issue kindly comment below
Hope it helps

Add below link for delete record
Delete

You can simply use an onclick function in your tag like
Delete

<div class="container">
<div class="row justify-content-center">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h4>View All Users</h4>
#if(session()->get('success'))
<div class="alert alert-success">
{{ session()->get('success') }}
</div>
#endif
#if(session()->get('danger'))
<div class="alert alert-danger">
{{ session()->get('danger') }}
</div>
#endif
</div>
<div class="card-body">
<div class="text-center my-2">
New User
</div>
<div>
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Username</th>
<th colspan="2">Actions</th>
</tr>
</thead>
<tbody>
#foreach($users as $user)
<tr>
<th>{{$user->id}}</th>
<td>{{$user->name}}</td>
<td>{{$user->email}}</td>
<td>{{$user->username}}</td>
<td class="text-center">
Show
Edit
Delete
</td>
</tr>
#endforeach
</tbody>
</table>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).on('click','.deleteUser',function() {
var url = $(this).attr('rel');
if(confirm("Are you sure you want to delete this?")){
window.location.href = url
}
else{
return false;
}
})
</script>
or
you can use any plugin like
http://myclabs.github.io/jquery.confirm/
http://bootboxjs.com/
In controller
```php
public function deleteposts(Request $request)
{
// your delete code is here
$request->session()->flash('success', 'Post deleted sucessfully');
return redirect()->back();
}
here you setting success message

Related

ajax or jquery doesn't show data Laravel

I added a search field to show live my data, but nothing works when I fill that field.
I made a route called retour.action, and that's in my controller, so when I try a console.log('test') i can see test in my Console on my browser, but the rest of the code I made doesn't work, and I also get no error
here is my controller
public function action(Request $request)
{
if ($request->ajax()) {
$output = '';
$query = $request->get('query');
if ($query != '') {
$retours = Returnorder::all()
->where('firmaname', 'like', '%' . $query . '%')
->orWhere('ordernumber', 'like', '%' . $query . '%')
->orWhere('status', 'like', '%' . $query . '%')
->get();
} else {
$retours = Returnorder::latest('id')->paginate(15);
}
$total_row = $retours->count();
if ($total_row > 0) {
foreach ($retours as $retour) {
$output .= '
<tr>
<td>' . $retour->firmaname . '</td>
<td>' . $retour->ordernumber . '</td>
<td>' . $retour->status . '</td>
</tr>
';
}
} else {
$output = '<tr>
<td align="center" colspan="5">Geen data gevonden</td>
</tr>
';
}
$retours = array(
'table_data' => $output,
);
echo json_encode($retours);
}
}
And this is my script
$(document).ready(function(){
fetch_customer_data();
function fetch_customer_data(query = '')
{
$.ajax({
url:"{{ route('retour.action') }}",
method:'GET',
data:{query:query},
dataType:'json',
success:function(retours)
{
$('tbody').html(retours.table_data);
}
})
}
$(document).on('keypress', '#search', function(){
let query = $(this).val();
fetch_customer_data(query);
});
});
And the HTML is this
#extends('layouts.app')
#section('content')
<div class="container">
<div class="mTop">
<div class="row justify-content-center">
<div class="col-md-10">
#if(session('message'))
<div class="alert alert-success" role="alert">
{{session('message')}}
</div>
#endif
<div class="card">
<div class="card-header">Retourmeldingen</div>
<div class="card-body">
<div class="form-group" >
<label for="search" hidden>Zoeken</label>
<input type="text" name="search" id="search" class="form-control"
placeholder="Typ hier uw zoekopdracht in"/>
</div>
<table class="table table-hover">
<thead>
<tr>
<th scope="col">Firmanaam</th>
<th scope="col"></th>
<th scope="col"></th>
<th scope="col">Ordernummer</th>
<th scope="col">Status</th>
<th scope="col">Verwerkingstijd</th>
<th scope="col">Inzenddatum</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
Help me please
I think you first need to be sure that what you're typing is actually being sent back to the router. You can get the value of what you're typing by using this:
$(function() {
$('#search').on('keyup', (e) => {
console.log(e.target.value);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="search" type="text" name="search" />

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

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.

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