I create a page on which there is a table with a paginator. I post a request to specify the output of rows from the database for insertion into the table. However, the paginator remains old. How should I change it?
Get a request for a new page or insert all the HTML code that comes from the controller is not satisfied.
Code view:
<table class="table table-bordered text-center table-hover" id="table_list">
<thead>
<tr>
<th>id</th>
</tr>
<tr>
<td><input type="text" class="form-control" id="id_card" value=""></td>
</tr>
</thead>
<tbody>
#if($dats)
#foreach($dats as $data)
<tr>
<td><div class="help" data-id="{{ $data['id'] }}"> {{$data['id']}}</div></td>
</tr>
#endforeach
#endif
</tbody>
</table>
{{ $dats->links() }} // After completing the ajax, the link remains old and allows you to navigate through the old table
Js code in view:
$('#id_card').on('keyup', function(){ // search
value = $(this).val();
$.ajax({
type: 'POST',
url: '/home',
data: {
search: value,
code: 1,
_token: '{{csrf_token()}}'
},
success: function (data) {
$('#table_list').empty();
$('#table_list').append(data); // update table
//update paginator links
},
error: function(data){
console.log(data);
}
})
})
Code controller
public function search(Request $request){
$models= Model::where('table','LIKE','%'.$request->input('search').'%')->paginate(4);
$str = "";
foreach($models as $model){
$str .= '<tr>'.
'<td>'. $model["id"].'</td>'.
'</tr>';
}
print($str);
return;
}
In Laravel 5, you could do it by changing your controller to something like this.
public function search(Request $request){
$models= Model::where('table','LIKE','%'.$request->input('search').'%')->paginate(4);
$str = "";
foreach($models as $model){
$str .= '<tr>'.
'<td>'. $model["id"].'</td>'.
'</tr>';
}
return response()->json([
'rows' => $str,
'links' => $models->render()
], 200);
}
In your ajax response, render the links with $('ul.pagination').replaceWith(data.links);
eg.
$.ajax({
type: 'POST',
url: '/home',
data: {
search: value,
code: 1,
_token: '{{csrf_token()}}',
page: page
},
success: function (data) {
$('#table_list').empty();
$('#table_list').append(data.rows); // update table
$('ul.pagination').replaceWith(data.links); // update links
},
error: function(data){
console.log(data);
}
});
Related
I'm just trying to send the editable table row data to the controller onClick of the Save button, update that data in the database, and return success.
But I cannot display the data inside the controller function of laravel. Data inside saveMe function is coming as desired as shown in below screenshot but it is not going to the controller
<table id="customersTable" class="table table-bordered table-responsive-md table-striped text-center" style="border-style: solid; border-color:red">
#php
$customersData = Session::get('data');
$issues = Session::get('issues');
#endphp
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Contact</th>
<th>Address</th>
<th>Name</th>
</tr>
</thead>
<tbody id="bodyData">
#foreach ($customersData as $key => $data)
<form action="ajaxform">
<!-- This is our clonable table line -->
<tr>
<td>{{$key}}</td>
<td name="name" class="pt-3-half name" contenteditable="true"
value={{$data['name']}} data-id={{$key}}>
{{$data['name']}}
</td>
<td name="email" class="pt-3-half email" contenteditable="true"
value={{$data['name']}} data-id={{$key}}>
{{$data['email']}}
</td>
<td>
<div class="test">
<span class="table-save">
<button type="button" onclick="saveMe(this)" class=" btn btn-secondary btn-rounded btn-sm my-0 saveBtn">
Save
</button>
</span>
</div>
</td>
</tr>
</form>
#endforeach
</tbody>
</table>
JavaScript function
<script>
function saveMe(params) {
var tr = $(this).closest("tr"); //get the parent tr
var name = $(params).closest("tr").find(".name").text();
var email = $(params).closest("tr").find(".email").text();
console.log(name);
console.log(email);
$.ajax({
url: '/customers/saveSingleRecord',
type: 'GET',
data: {
_token:'{{ csrf_token() }}',
value: {
'name' : name,
'email' : email,
'contact' : contact,
'address' : address,
},
},
success: function(data){
alert("success");
}
});
}
Function inside the controller
class CustomersController extends Controller
{
public function saveSingleRecord(Request $request)
{
// $name = $_GET['name'];
$name = $request->name;
dd($name); // <------------------ Not showing anything
// return response()->json($name);
}
}
Route inside web.php
Route::post('/customers/saveSingleRecord/', [CustomersController::class, 'saveSingleRecord']);
In your ajax request you are passing your data inside value attribute so it's not showing. If you try $request->value['name'] then it will show you the name. If you want to get name directly in request object then pass as like below.
$.ajax({
url: '/customers/saveSingleRecord',
type: 'GET',
data: {
_token:'{{ csrf_token() }}',
'name' : name,
'email' : email,
'contact' : contact,
'address' : address,
},
success: function(data){
alert("success");
}
});
The correct way to send ajax is below
$.ajax({
url: '/customers/saveSingleRecord',
type: 'GET',
data: {
name : name,
email : email,
contact : contact,
address : address,
_token :'{{ csrf_token() }}',
},
success: function(data){
alert("success");
}
});
Basically you set key value pair within data.
So the situation is such:
I am using data-tables in my .cshtml file. I have managed to add records via a modal but the issue is when i want to populate a modal in order to edit the data from a row. I do not wish to fetch data from the row but instead do a Ajax request to fetch the data. Below shows the structure of my table
<table id="example" class="table table-striped table-bordered dt-responsive display nowrap" cellspacing="0">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Username</th>
<th>Email</th>
<th>Status</th>
<th>Roles</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach (var user in Model.Users)
{
<tr>
<td>#user.FirstName</td>
<td>#user.LastName</td>
<td>#user.UserName</td>
<td>#user.Email</td>
<td>#user.status</td>
<td>
#{ if (user.Roles.Contains("SuperAdmin"))
{
<span class="badge badge-danger">SA</span> }
else if (user.Roles.Contains("Admin"))
{
<span class="badge badge-danger">ADMIN</span> }
else if (user.Roles.Contains("Moderator"))
{
<span class="badge badge-warning">MOD</span> }
else if (user.Roles.Contains("Basic"))
{
<span class="badge badge-success">BASIC</span> }
}
</td>
<td>
#{ if (user.Roles.Contains("SuperAdmin"))
{
<span class="badge badge-warning">Locked</span> }
else
{
<button class="btn btn-sm btn-dark details" id="useredit" data-id="#user.UserId">Edit</button>
<a class="btn btn-primary btn-sm" asp-area="Identity" asp-page="/Account/UserRoles" asp-route-userId="#user.UserId">Manage Roles</a> }
}
</td>
</tr>}
</tbody>
</table>
When i click on the edit button the follow code gets executed
$("button.details").on('click', function () {
console.log({ "id": $(this).attr("data-id") });
var userid = $(this).attr("data-id");
$.ajax({
type: "POST",
url: "/Identity/Account/Users?handler=UsersAsJson",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: { id:userid },
contentType: "json; charset=utf-8",
success: function (regions) {
console.log(regions)
},
failure: function (response) {
alert(response);
}
});
});
And this is the handler function below
public async Task<IActionResult> OnPostUsersAsJsonAsync(string? id)
{
System.Diagnostics.Debug.WriteLine("id passed",id);
return new JsonResult(id);
}
Can anyone tell me how do we pass the id from the ajax request into the handler function? cause at the moment its not posting to the OnPostUsersAsJsonAsync function.
Also note i have tried getJSON without any success.
For you do not have a form,be sure you have added token like below:
<button class="btn btn-sm btn-dark details" id="useredit" data-id="#user.UserId">Edit</button>
#Html.AntiForgeryToken()
Change your js like below:
#section Scripts
{
<script>
$("button.details").on('click', function () {
console.log({ "id": $(this).attr("data-id") });
var userid = $(this).attr("data-id");
$.ajax({
type: "POST",
url: "/Identity/Account/Users?handler=UsersAsJson",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: { id: userid },
//contentType: "json; charset=utf-8", //remove this line
success: function (regions) {
console.log(regions)
},
failure: function (response) {
alert(response);
}
});
});
</script>
}
Startup.cs:
services.AddRazorPages();
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN"); //be sure add this line
Result:
So I've been learning Laravel and was getting into making DataTables. However, my 'editItem' route is not being able to get any information when I click 'Edit' button. It shows Error 405.
DataTable view (dt.blade.php) -
HTML part where the table is displayed
<div class="table-responsive text-center">
<table class="table table-borderless" id="table">
<thead>
<tr>
<th class="text-center">ID</th>
<th class="text-center">Name</th>
<th class="text-center">Created At</th>
<th class="text-center">Updated At</th>
<th class="text-center">Actions</th>
</tr>
</thead>
#foreach($users as $user)
<tr class="user{{$user->id}}">
<td >{{$user->id}}</td>
<td>{{$user->name}}</td>
<td>{{$user->created_at}}</td>
<td>{{$user->updated_at}}</td>
<td><button class="edit-modal btn btn-info"
value="{{$user->id}},{{$user->name}}">
<span class="glyphicon glyphicon-edit"></span> Edit
</button>
<button class="delete-modal btn btn-danger"
value="{{$user->id}},{{$user->name}}">
<span class="glyphicon glyphicon-trash"></span> Delete
</button></td>
</tr>
#endforeach
</table>
</div>
JS part in the same file
<script>
$(document).ready(function() {
$('#table').DataTable();
} );
</script>
<script>
$(document).on('click', '.edit-modal', function() {
$('#footer_action_button').text("Update");
$('#footer_action_button').addClass('glyphicon-check');
$('#footer_action_button').removeClass('glyphicon-trash');
$('.actionBtn').addClass('btn-success');
$('.actionBtn').removeClass('btn-danger');
$('.actionBtn').removeClass('delete');
$('.actionBtn').addClass('edit');
$('.modal-title').text('Edit');
$('.deleteContent').hide();
$('.form-horizontal').show();
var stuff = $(this).val().split(',');
console.log($(this).val());
fillmodaluser(stuff)
$('#myModal').modal('show');
});
$(document).on('click', '.delete-modal', function() {
$('#footer_action_button').text(" Delete");
$('#footer_action_button').removeClass('glyphicon-check');
$('#footer_action_button').addClass('glyphicon-trash');
$('.actionBtn').removeClass('btn-success');
$('.actionBtn').addClass('btn-danger');
$('.actionBtn').removeClass('edit');
$('.actionBtn').addClass('delete');
$('.modal-title').text('Delete');
$('.deleteContent').show();
$('.form-horizontal').hide();
var stuff = $(this).val().split(',');
console.log($(this).val('info'));
$('.did').text(stuff[0]);
$('.dname').html(stuff[1]);
$('#myModal').modal('show');
});
function fillmodaluser(details){
$('#fid').val(details[0]);
$('#name').val(details[1]);
}
$('.modal-footer').on('click', '.edit', function() {
$.ajax({
type: 'post',
url: '../public/editUser',
user: {
'_token': $('input[name=_token]').val(),
'id': $('#fid').val(),
'name': $('#name').val()
},
success: function(user) {
if (user.errors){
$('#myModal').modal('show');
if(user.errors.name) {
$('.name_error').removeClass('hidden');
$('.name_error').text("Name can't be empty !");
}
if(user.errors.email) {
$('.email_error').removeClass('hidden');
$('.email_error').text("Email must be a valid one !");
}
}
else {
$('.error').addClass('hidden');
$('.user' + users.id).replaceWith("<tr class='users" + users.id + "'><td>" +users.id + "</td><td>" + users.name+"</td><td>" + "</td><td>" + "</td><td><button class='edit-modal btn btn-info' user-info='" + users.id+","+users.name+"'><span class='glyphicon glyphicon-edit'></span> Edit</button> <button class='delete-modal btn btn-danger' user-info='" + users.id+","+users.name+"' ><span class='glyphicon glyphicon-trash'></span> Delete</button></td></tr>");
}}
});
});
$('.modal-footer').on('click', '.delete', function() {
$.ajax({
type: 'post',
url: '../public/deleteUser',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
user: {
'_token': $('input[name=_token]').val(),
'id': $('.did').text()
},
success: function(user) {
$('.user' + $('.did').text()).remove();
}
});
});
</script>
And lastly, the web.php
Route::get('/dt', 'UserController#dt');
Route::get('/editUser', function (Request $request) {
$rules = array (
'name' => 'required|alpha',
);
$validator = Validator::make(Input::all(), $rules );
if ($validator->fails ())
return Response::json ( array (
'errors' => $validator->getMessageBag()->toArray ()
) );
else {
$user->id = User::find ( $request->id );
$user->name = ($request->name);
$user->save ();
return response ()->json ( $user );
}
});
Route::get ('/deleteUser', function (Request $request) {
User::find ( $request->id )->delete ();
return response ()->json ();
});
The JSON error that shows to me is "{"errors":{"name":["The name field is required."]}}"
My question is that, the info can be split fine in the JQuery here when I press the Edit button; it is able to show the info of the row I've selected. I don't understand why the same values aren't getting sent to my editUser route?
change all get method to post , because you are using post in client side
Route::post('/dt', 'UserController#dt');
Route::post('/editUser', function (Request $request) {
$rules = array (
'name' => 'required|alpha',
);
$validator = Validator::make(Input::all(), $rules );
if ($validator->fails ())
return Response::json ( array (
'errors' => $validator->getMessageBag()->toArray ()
) );
else {
$user->id = User::find ( $request->id );
$user->name = ($request->name);
$user->save ();
return response ()->json ( $user );
}
});
Route::post ('/deleteUser', function (Request $request) {
User::find ( $request->id )->delete ();
return response ()->json ();
});
Seems your urls should not be '../public/' (in your ajax requests) but it should match what you typed in your file web.php
Hi i have this delete button which i really want to pass using ajax call. My problem is that when the delete button is clicked this is the error that i get
NetworkError: 405 Method Not Allowed and (1/1) MethodNotAllowedHttpException. This is my code below
<script type="text/javascript">
$(document).ready(function(){
$('.delete-block').on("click","a#deleteBtn", function() {
var x = confirm("Do you want to delete this?");
if(x){
var id = $(this).data("deleteid");
$.ajax({
type:"post",
url: $(this).data("href"),
data: {
id: id
},
success: function(data){
$("#deleteId"+ id).fadeOut('slow');
}
});
return true;
}else{
return false;
}
return false;
});
});
</script>
<tbody>
#foreach($datas as $post)
<tr class="delete-block" id="deleteId{{ $post['id'] }}">
<td>{{ $post['title']}}</td>
<td>{{ $post['post'] }} </td>
<td>{{ $post['comments'] }}</td>
<td>
Edit
Delete
</td>
</tr>
#endforeach
</tbody>
Im using the action('AddRecordController#destroy', $post['id']) since my AddRecordController is being generated. And my route is only this one
Route::resource('addRecord', 'AddRecordController');
My AddRecordController code below
public function destroy($id){
//
echo "Test";
echo $id;
$addRecord = Addrecord::find($id);
$addRecord->delete();
}
Can someone help me figured this thing out? Any help is muchly appreciated.
TIA.
You need to use the DELETE method. You can use form method spoofing to do this.
Try this:
<script type="text/javascript">
$(document).ready(function(){
$('.delete-block').on("click","a#deleteBtn", function() {
var x = confirm("Do you want to delete this?");
if(x){
var id = $(this).data("deleteid");
$.ajax({
type:"post",
url: $(this).data("href"),
data: {
id: id,
"_method": "delete"
},
success: function(data){
$("#deleteId"+ id).fadeOut('slow');
}
});
return true;
}else{
return false;
}
return false;
});
});
</script>
<tbody>
#foreach($datas as $post)
<tr class="delete-block" id="deleteId{{ $post['id'] }}">
<td>{{ $post['title']}}</td>
<td>{{ $post['post'] }} </td>
<td>{{ $post['comments'] }}</td>
<td>
Edit
Delete
</td>
</tr>
#endforeach
</tbody>
I'm working on a php online shop website using codeigniter framework and i want to be able to filter my table results using checkboxes with ajax
view:
<input type="checkbox" name="brand" value="acer">
<input type="checkbox" name="brand" value="lenovo">
<input type="checkbox" name="pret" value="1000">
<table>
<tbody>
<?php foreach ($laptops_toate as $laptops_all) { ?>
<tr>
<td><img src="http://localhost:82/ci/images/emag/<?php echo $laptops_all->file ?>"></td>
<td><p>Laptop <?php echo $laptops_all->brand ?> </p>
</td>
</tr>
<?php } ?>
</tbody>
</table>
Controller:
public function laptops()
{
$filter = array(
'pret' => $this->input->get('pret'),
'brand' =>$this->input->get('brand')
);
$data['laptops_toate'] = $this->emag_model->laptops_toate_grid($filter);
$this->renders('emag/laptops', $data);
}
model:
public function laptops_toate_grid($filter = null){
$this->db->select('*')
->from('laptop_notebook');
// $query = $this->db->get('laptop_notebook')->result();
// return $query;
if($filter['brand']){
$this->db->where('brand', $filter['brand']);
}
if($filter['pret']){
$this->db->where('pret', $filter['pret']);
}
$query = $this->db->get()->result();
return $query;
}
The problem is now at the ajax code, i don't know how to send the data filter to the server in order to receive the success function.
View:
<script>
$("input[checkbox]").change(function(){
$.ajax({
url: route,
dataType: 'json',
success: function(data){
$.each(data, function(index, element) {
$("tbody").empty();
$("tbody").append("<tr><td>"+
"Laptop "+element.brand+""+
"</td></tr>");
});
}
});
Controller:
public function laptops()
{
$filter = array(
'pret' => $this->input->get('pret'),
'brand' =>$this->input->get('brand')
);
echo json_encode($this->emag_model->laptops_toate_grid($filter));
}
Now just do console.log(data); first inside the $.each() to see what your array looks like.