Retrieving table row information using ajax and pdo to display in bootstrap modal - ajax

Im trying to retrieve information from a table which is populated by a PDO array into a html table. I want to grab the row information when a user clicks on the 'delete button' for that row into a modal which i have for the delete confirmation.
I'm not sure how to go about doing this because the information returned is from the database and not hard-coded in.
<table class="table table-bordered table-hover" id="tab_logic">
<thead>
<tr >
<th class="text-center">
Course Code
</th>
<th class="text-center">
Course Title
</th>
</tr>
</thead>
<tbody>
<?php foreach ($courses as $row) {
echo "<tr><td>";
echo $row['course_code'];
echo "</td><td>";
echo $row['course_title'];
echo "</td><td>";
echo '<p data-placement="top"
data-toggle="tooltip"
style="margin-left:18px"
title="Delete">';
echo '<button class="btn btn-danger btn-xs"
data-title="Delete"
data-toggle="modal"
data-target="#delete">';
echo '<span class="glyphicon glyphicon-trash" />';
echo '</button></p>';
echo "</tr>"; }
?>
this is the code for the modal:
<div id="delete" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Delete Record</h4>
</div>
<div class="modal-body">
<p class="text-danger"><small>Are you sure you would like to delete this record?</small></p>
<p class="text-danger"><small>You will not be able to un-do this action</small></p>
<div class="form-group">
<input class="form-control " type="text" placeholder="Course Title">
</div>
</div>
<div class="modal-footer">
<button id="can" type="button" class="btn btn-warning" data-dismiss="modal">Cancel</button>
<button id= "upd" type="submit" class="btn btn-danger">Delete</button>
</form>
</div>
</div>
</div>
</div>
I know i will need AJAX to do this dynamically. Does anyone have any ideas of a solution? thanks

Here's the solution.
http://getbootstrap.com/javascript/#modals-related-target
You should add a new data attribute here:
'<button class="btn btn-danger btn-xs"
data-title="Delete"
data-index="yourItemIndex" <----- here
data-toggle="modal"
data-target="#delete">';
Your script should be something like this:
$('#exampleModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var recipient = button.data('whatever') // Extract info from data-* attributes
// If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
// Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
var modal = $(this)
modal.find('.modal-title').text('New message to ' + recipient)
modal.find('.modal-body input').val(recipient)
})
Best regards.

Related

DataTables warning: table id=category_table - Invalid JSON response. datatable ajax laravel

i am using delete method to destroy an item of the category table but when i reload the datatable function ajax it gives me an error DataTables warning: table id=category_table - Invalid JSON response. i don't know why it returns this error please help i want to refresh the table without refreshing the website
note:the delete method works fine
my table
<h1>all categories</h1>
<table class="table" id="category_table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">name</th>
<th scope="col">edit</th>
<th scope="col">delete</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
my ajax code
<script>
$(document).ready(function(){
$('body').on('click','#delete',function(){
var id = $(this).val();
$('#deleteexampleModal').modal('show');
$("#deleteid").val(id);
});
});
$('#deleteform').submit(function(e){
e.preventDefault();
var id = $("#deleteid").val();
// console.log(id);
$.ajax({
url: 'categories/'+id,
type: "DELETE",
dataType: 'json',
success:function(response){
console.log(response);
$("#deleteexampleModal").modal('hide');
// window.location.reload();
$('#category_table').DataTable().ajax.reload();
}
});
});
and my modal when clicking the delete button
<!-- delete Modal -->
<div class="modal fade" id="deleteexampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Add new Product</h5>
<button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form method="POST" id="deleteform" name="form">
#csrf
#method('DELETE')
<div class="form-group">
are you sure you want to delte this item?
<input type="text" id="deleteid" name="deleteid">
</div>
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save changes</button>
</form>
</div>
<div class="modal-footer">
</div>
</div>
</div>
my delete method
public function deleteCategory($id){
$category = Category::find($id)->delete();
return response()->json([
'status' => 200,
'message' => 'deleted succfully'
]);
}

Problem with Laravel CRUD (Edit Function)

Good day everyone. I'm quite new to new to Laravel and was doing some basic CRUD coding, I was able to code the add and view function, but I'm having a hard time with the edit and delete function.
I have 4 files, the master blade file, the web.php (routing), the blade file and the Form Controller.
This is the promo.blade.php file:
<table class="table table-striped" id="table1" >
<thead>
<tr>
<th class="text-center">ACTION</th>
<th class="text-center">Offer ID</th>
<th class="text-center">Promo Name</th>
<th class="text-center">Promo Price</th>
<th class="text-center">Status</th>
</tr>
</thead>
<tbody>
#foreach ($data as $key => $item)
<tr>
<td class="text-center">
<a href="#" data-bs-toggle="modal" data-bs-target="#show" data-myofferid="{{$item->offerId}}" data-mytitle="{{$item->promoName}}" data-myprice="{{$item->promoPrice}}">
<span class="badge bg-success"><i class="bi bi-eye-fill"></i></span>
</a>
<a href="#" data-bs-toggle="modal" data-bs-target="#edit" data-mainid="{{$item->id}}" data-myofferid="{{$item->offerId}}" data-mytitle="{{$item->promoName}}" data-myprice="{{$item->promoPrice}}">
<span class="badge bg-primary"><i class="bi bi-pencil-square"></i></span>
</a>
<a href="#" data-bs-toggle="modal" data-bs-target="#delete" data-myofferid="{{$item->offerId}}" data-mytitle="{{$item->promoName}}" data-myprice="{{$item->promoPrice}}">
<span class="badge bg-danger"><i class="bi bi-trash"></i></span>
</a>
</td>
<td class="date text-center">{{ $item->offerId }}</td>
<td class="date text-center">{{ $item->promoName }}</td>
<td class="number text-center">{{ $item->promoPrice}}</td>
<td class="number text-center">{{ $item->isActive }}</td>
</tr>
#endforeach
</tbody>
</table>
<!--Start Modal Edit -->
<div class="modal fade text-left" id="edit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel160" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-dialog-scrollable" role="document">
<div class="modal-content">
<div class="modal-header bg-primary">
<h5 class="modal-title white" id="add">
Edit Promo
</h5>
<button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
<i data-feather="x"></i>
</button>
</div>
<div class="modal-body">
<form action="{{ route('promo.edit') }}" method="POST">
#csrf
<div class="form-group">
<label for="">ID</label>
<input type="text" class="form-control" name="id" id="id" value="">
<span style="color:red">#error('id'){{$message}} #enderror</span>
</div>
<div class="form-group">
<label for="">Offer ID</label>
<input type="text" class="form-control" name="offerId" id="offerId" value="">
<span style="color:red">#error('offerId'){{$message}} #enderror</span>
</div>
<div class="form-group">
<label for="">Promo Name</label>
<input type="text" class="form-control" name="promoName" id="promoName" value="">
<span style="color:red">#error('promoName'){{$message}} #enderror</span>
</div>
<div class="form-group">
<label for="">Promo Price</label>
<input type="number" class="form-control" name="promoPrice" id="promoPrice" value="">
<span style="color:red">#error('promoPrice'){{$message}} #enderror</span>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light-secondary" data-bs-dismiss="modal">
<i class="bx bx-x d-block d-sm-none"></i>
<span class="d-none d-sm-block">CANCEL</span>
</button>
<button type="submit" class="btn btn-primary ml-1">
<i class="bx bx-check d-block d-sm-none"></i>
<span class="d-none d-sm-block">SAVE</span>
</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- End Modal Edit-->
Then this is the web.php file, for the routing:
Route::get('promo.promo', [App\Http\Controllers\FormControllerPromo::class, 'viewRecord'])->middleware('auth')->name('promo.promo');
Route::post('promo.add', [App\Http\Controllers\FormControllerPromo::class, 'addPromo'])->name('promo.add');
Route::post('promo.delete/{id}', [App\Http\Controllers\FormControllerPromo::class, 'viewDelete'])->middleware('auth');
Route::get('promo.edit', [App\Http\Controllers\FormControllerPromo::class, 'viewRecord'])->middleware('auth')->name('promo.edit');
Route::get('promo.edit/{id}', [App\Http\Controllers\FormControllerPromo::class, 'viewDetail'])->middleware('auth');
Route::post('promo.edit', [App\Http\Controllers\FormControllerPromo::class, 'edit'])->name('promo.edit');
This is the master.blade.php file:
<!--Start Modal edit for Promo-->
<script type="text/javascript">
$('#edit').on('show.bs.modal', function (event){
var button = $(event.relatedTarget)
var mainid = button.data('mainid')
var id = button.data('myofferid')
var title = button.data('mytitle')
var price = button.data('myprice')
var modal = $(this)
modal.find('.modal-body #id').val(mainid);
modal.find('.modal-body #offerId').val(id);
modal.find('.modal-body #promoName').val(title);
modal.find('.modal-body #promoPrice').val(price);
})
</script>
<!--End Modal edit for Promo-->
I think this is the part where the code wont execute properly.
This is the FormControllerPromo.php file:
// view form
public function index()
{
return view('promo.promo');
}
// view record
public function viewRecord()
{
$data = DB::table('promo')->get();
return view('promo.promo',compact('data'));
}
// view detail
public function viewDetail($id)
{
$data = DB::table('promo')->where('id',$id)->get();
return view('promo.promo',compact('data'));
}
// edit promo
public function edit(Request $request){
$id = $request->input('id');
$offerId = $request->input('offerId');
$promoName = $request->input('promoName');
$promoPrice = $request->input('promoPrice');
DB::table('promo')
->where('id', $id) // find your user by their email
->limit(1) // optional - to ensure only one record is updated.
->update(array('offerId' => $offerId, 'promoName' => $promoName, 'promoPrice' => $promoPrice)); // update the record in the DB.
$data = DB::table('promo');
return view('promo.promo',compact('data'));
}
I've been trying to code this for almost a week now with no success, any help is highly appreciated. :)
the update seems right, should work. but when you pass the $data variable to your view, you should call ->get(), because otherwise you return a query builder instance, that later raises the Undefined property error when trying to access {{$item->offerId}}.
change second last line in your example
//from this:
$data = DB::table('promo');
//to this:
$data = DB::table('promo')->get();
//or to this if you want to show only one record:
$data = DB::table('promo')->where('id', $id)->get();

Trying to delete data using modal popup, not getting correct id of selected item

I have a table view with many records and I want to have a delete button for each record, which will prompt a modal box for the user to confirm a delete. I am able to have the correct buttons (viewed from the table) to prompt the modal, but the button within the modal, which is the button to confirm a delete doesnt pass the right id. For example, I have 3 records in my table that is shown, with an ID of 1, 2 and 3. But the way I have code my table (will show code below) makes it where the user clicks any of the delete button on the desired record, the modal box pops up, with the "Delete(confirm)" button with an ID of the newest amongst all records. In this situation would be an ID of 3. I want it to pass the correct ID. Meaning if I want to delete record 1 it will pass ID 1 and record 2 and so on
I have tried researching what I did wrongly with my JavaScript but it seems ok and nothing seems to help for now. I have tried putting the whole modal into my table but it still has the same problem...
<!-- DataTables Example -->
<div class="card mb-3">
<div class="card-header">
<i class="fas fa-table"></i>
Advertisements
<div></div>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th>Title</th>
<th>Description</th>
<th>Image</th>
<th>Status</th>
<th>Sort No.</th>
<th>Updated By</th>
<th>Expired At</th>
<th>Updated At</th>
<th> </th>
<th> </th>
</tr>
</thead>
<tbody>
#foreach ($advertisements as $advertisement)
<tr>
<td>{{ $advertisement->media->title }}</td>
<td>{{ $advertisement->media->description }}</td>
<td><img src="{{asset('/storage/uploads/images/').'/'.$advertisement->image}}" height="65" width="100"></td>
#php
if ($advertisement->media->status == 1){
$current_status = 'Active';
} elseif ($advertisement->media->status == 0){
$current_status = 'Inactive';
}
#endphp
<td>{{ $current_status }}</td>
<td>{{ $advertisement->media->sort}}</td>
<td>{{ $advertisement->media->admin->username}}</td>
<td>{{ $advertisement->expired_at}}</td>
<td>{{ $advertisement->media->updated_at}}</td>
<td><a href="/advertisements/{{$advertisement->id}}/edit" class="btn btn-success">Edit</td>
<td>
<button class="btn btn-danger delete-record" data-toggle="modal" data-target="#deleteModal" data-id="{{$advertisement->id}}" data-url="/advertisements/{{$advertisement->id}}">Delete , {{$advertisement->id}}</button>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
<div class="card-footer small text-muted">Updated yesterday at 11:59 PM</div>
</div>
Above code is the table view showing my data, and each record will have a delete button next to it.
<form action="" method="post" id="deleteForm">
#method('DELETE')
#csrf
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Are you sure you want to delete this record?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="delete" class="btn btn-danger">Delete</button>
</div>
</div>
</div>
</div>
</form>
The code above is my modal box code, with a form that creates a delete request.
The code below is the javascript that is handling the delete and the passing of id and the action:-
$(document).ready(function () {
$('.delete-record').click(function () {
var url = $(this).attr('data-url');
$("#deleteForm").attr("action", url);
});
});
I want it to pass the correct ID. Meaning if I want to delete record 1 it will pass ID 1 and record 2 and so on.
You try to send your form via POST method, but there is no post data such as advertising id in it.
Can you please show your web.php route file ?
Because if it's POST method here, you should to add hidden input in your form.
Try with this,
Instead of url you should use route,
<button class="btn btn-danger delete-record" data-toggle="modal" data-target="#deleteModal" data-id="{{$advertisement->id}}" data-action="{{ route('advertisements.destroy', $advertisement->id) }}">Delete , {{$advertisement->id}}</button>
In your JS code
$("#deleteForm").attr("action", $(this).data('action'));
And if you don't put your modal code outside foreach then put it in at end of file
Hope this helps :)

pass data from table to modal using angular

Im using Spring MVC and AngularJS to build my app and I been looking for a way to pass a table registry data to a modal in order to edit that registry but I haven´t find a working example so, thats my question how can a I pass the registry data to a modal?
This is what I have so far:
Table
<table class="table table-hover table-responsive">
<thead class="table-striped">
<th>Email</th>
<th>Nombre</th>
<th>Apellidos</th>
<th>Rol</th>
<th>Acciones</th>
</thead>
<tbody>
<tr data-ng-show="allUsuarios.length === 0">
<td colspan="4" class="warning">No hay registros para mostrar</td>
</tr>
<tr data-ng-repeat="usuarios in allUsuarios">
<td>{{usuarios.email}}</td>
<td>{{usuarios.nombre}}</td>
<td>{{usuarios.apellidos}}</td>
<td>{{usuarios.idRol.tipoRol}}</td>
<td>
<input type="hidden" value="{{usuarios.idUsuario}}"/>
<button class="btn btn-primary" data-toggle="modal" data-target="#formModalEditar"><i class="glyphicon glyphicon-pencil"></i></button>
<button class="btn btn-danger" data-toggle="modal" data-target="#formModalEliminar"><i class="glyphicon glyphicon-trash"></i></button>
</td>
</tr>
</tbody>
</table>
And the Modal:
<!--EDIT MODAL-->
<div class="col-lg-12">
<div class="modal fade" id="formModalEditar" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="H2">Editar Usuario</h4>
</div>
<div class="modal-body">
<form role="form" action="add" method="post">
<div class="form-group">
<label>Email</label>
<input class="form-control" type="text" required=""/>
<label>Nombre</label>
<input class="form-control" type="text" required=""/>
<label>Apellidos</label>
<input class="form-control" type="text" required=""/>
<label>Rol</label>
<br>
<div class="btn-group open">
<button data-toggle="dropdown" class="btn dropdown-toggle">Action <span class="caret"></span></button>
<ul class="dropdown-menu">
<li>Action</li>
</ul>
</div>
</div>
<div class="text-right">
<button type="submit" class="btn btn-success">Guardar</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<!--END EDIT MODAL-->
PS: I don´t know why when I press Ctrl+K to format the code, it gets displayed like that, sorry.
First of all you have to define a registery in you angular component
currentRegistery : Registery;
In your table you have to add an onclick on the edit icon of each registery to be able to set the current Registery with the selected registery
<button class="btn btn-primary" data-toggle="modal" data-target="#formModalEditar" onclick=“currentRegistery=usuarios”><i class="glyphicon glyphicon-pencil"></i></button>
Finally on your modal you can deal directly with the currentRegistery object.

data tables couldnt work when thereis an bootstrap modal inside

I have a BIG PROBLEM, my data tables coundt work when i put a Bootstrap Modal in, the Bootstrap Modal is in the tr for Edit data for Looping.
here's my table and modal within
<table id="data" class="table table-bordered table-striped">
<thead>
<tr>
<th>No</th>
<th><center>Foto</center></th>
<th><center>Nip</center></th>
<th><center>Nama</center></th>
<th><center>Action</center></th>
</tr>
</thead>
<tbody>
<?php include( "../koneksi.php"); $no=1 ; $data_pegawai=m ysql_query( 'select * from data_pegawai'); while($data=m ysql_fetch_array($data_pegawai)){ ?>
<tr>
<td>
<?php echo $no; ?>
</td>
<td>
<?php echo $data[ 'foto']; ?>
</td>
<td>
<?php echo $data[ 'nip']; ?>
</td>
<td>
<?php echo $data[ 'nama']; ?>
</td>
<td>
<a class="btn btn-warning btn-md" data-toggle="modal" data-target="#myModalEdit<?php echo $data['id']; ?>"><span class="glyphicon glyphicon-pencil" aria-hidden="true"></span></a>
<a class="btn btn-danger btn-md"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span></a>
</td>
<td>
<!-- Dialog Modal Edit -->
<div class="modal fade" id="myModalEdit<?php echo $data['id']; ?>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel<?php echo $data['id']; ?>" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel<?php echo $data['id']; ?>">Edit Data</h4>
</div>
<div class="modal-body">
<form role="form" action="../master-pegawaiSimpan.php" method="post" enctype="multipart/form-data">
<div class="box-body">
<div class="form-group">
<div class="col-lg-12">
<label for="agama">Nip</label>
<input type="text" class="form-control" name="nip" placeholder="Nip" value="<?php echo $data['nip']; ?>">
<label for="agama">Nama</label>
<input type="text" class="form-control" name="nama" placeholder="Nama" value="<?php echo $data['nama']; ?>">
<br>
<label for="agama">Foto</label>
<input type="file" class="form-control" name="foto">
<br>
</div>
</div>
<div class="box-footer">
<button type="submit" value="Simpan" name="Simpan" class="btn btn-primary">Save</button>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</td>
</tr>
<?php $no++; } ?>
</tbody>
</table>
and i confused with the order of javascripts, did it make an effect?
So, if i delete the modal inside the table, data tables were fine
Your problem is a mismatch between the number of header <th> elements and the number column <td> elements. They must match exactly.
So you have two options :
Add an extra <th> element, or
Place the modal outside of the table. This is what you should do in my opinion. There is no reason what so ever for replicating the popover markup over and over, you could do something like this instead :
<a class="btn btn-warning btn-md" data-toggle="modal" data-target="#myModalEdit" edit-id="<?php echo $data['id']; ?>"><span class="glyphicon glyphicon-pencil" aria-hidden="true"></span></a>
remove id from the modal as well
<div class="modal fade" id="myModalEdit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
and add a click event to populate data from the row when the modal is about to be shown:
$('a[data-toggle="modal"]').on('click', function() {
$tr = $(this).closest('tr');
$('[name="nip"]').val($tr.find('td:eq(2)'));
$('[name="nama"]').val($tr.find('td:eq(3)'));
//etc
})

Resources