How to write an ajax script to delete an entry? - php

Good day!
Please tell me how to correctly implement the method of deleting a record of Laravel through Ajax. I wrote a script, but somehow it works very crookedly.
The script from the part works, but when you click on the delete button, the record does not disappear. It disappears only after reloading the page. And when I try to delete a fresh record, a route error just flies.
Route
Route::delete('/id{id}/delete', 'ProfileController#delete')->name('deletePost');
Form
<form action="{{route('deletePost', ['id' => $post->id])}}" method="post" id="formDelete">
#csrf #method('DELETE')
<button type="submit" id="delete" class="btn btn-outline-dark btn-sm mt-4">Удалить</button>
</form>
And my script
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#delete').on('click', function(e) {
e.preventDefault();
var $this = $(this),
data = $this.data();
$.ajax({
url: "{{route('deletePost', ['id' => $post->id])}}",
method: 'POST',
data: data,
success: function(data) {
$( data ).remove();
},
error: function(d) {
console.log(d);
}
})
})
</script>

You must first remove the ID from the route:
Route::delete('/id/delete', 'ProfileController#delete')->name('deletePost');
You must assign a class name to each html record(or row).
Like the following code:
<table>
<tbody>
#foreach($records as $record)
<tr class="myRow">
...
</tr>
#endforeach
</tbody>
</table>
Also, it is better to create a hidden input in each deletion form to hold the record ID. Like the following:
<form method="post" id="formDelete">
<input type="hidden" name="id" value="{{$record->id}}">
#csrf #method('DELETE')
<button type="submit" id="delete" class="btn btn-outline-dark btn-sm mt-4">Удалить</button>
</form>
Then, when a record is deleted by Ajax, you must delete the corresponding row by the specified class name in the success section of ajax code. Like the following code:
var data = $(this).closest("form").serialize();
$.ajax({
url: "{{route('deletePost')}}",
method: 'POST',
data: data,
success: function(data) {
$(this).closest("#myRow").remove();
},
error: function(d) {
console.log(d);
}
})
I hope it helps

Related

Ajax script for deleting records from the database does not work

I wrote a script that should delete a specific entry. The problem is that when you click on the delete button, the record does not disappear, you have to reload the page to make it disappear. And only the first record in the database is deleted, for example, if I click delete the record with id = 2, then the record with id = 1 will be deleted. And I just can not understand why this is happening.
This is my script
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function () {
$("body").on("click","#delete",function(e){
e.preventDefault();
var id = $(this).data('data-id');
var token = $("meta[name='csrf-token']").attr("content");
$.ajax({
url: "{{route('deletePost',['id' => $post->id])}}",
type: 'DELETE',
data: {_token: token, id: id},
success: function (response){
$("#deletePost").html(response.message);
}
});
return false;
});
});
</script>
Method
public function delete($id) {
$post = Profile::find($id);
$post->delete();
return response()->json([
'message' => 'deleted...'
]);
}
Route
Route::delete('/id{id}/delete', 'ProfileController#delete')->name('deletePost');
And html
<form action="{{route('deletePost', ['id' => $post->id])}}" method="post" id="formDelete">
#csrf #method('DELETE')
<button type="submit" id="delete" class="btn btn-sm btn-outline-danger py-0 mt-4" data-id="{{ $post->id }}">Удалить</button>
</form>
change
var id = $(this).data('data-id');
to
var id = $(this).data('id');
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function () {
$("body").on("click","#delete",function(e){
e.preventDefault();
var id = $(this).data('id');
var token = $("meta[name='csrf-token']").attr("content");
$.ajax({
url: "delete/"+id,
type: 'DELETE',
data: {_token: token, id: id},
success: function (response){
$("#deletePost").html(response.message);
// call your data get function here for disappear record after delele
}
});
return false;
});
});
</script>
Change the route to :
Route::delete('delete/{id}', 'ProfileController#delete')->name('deletePost');
Delete Method are just fine.
There are no need form for delete button
<button type="submit" id="delete" class="btn btn-sm btn-outline-danger py-0 mt-4" data-id="{{ $post->id }}">Удалить</button>
You wrongly access attribute data-id of button delete.
It should be
var id = $(this).data('id');
Or
var id = $(this).attr('data-id');

Ajax No Refresh when Deleting Data in a Table - Laravel

My problem is I can click the button but it is needed to refresh to delete it . it there something that is making my ajax code a problem why it is refreshing? I want a button when click delete it will automatically delete without refreshing.
my Button
<button type="button" data-client_id="{{ $client->id }}" class="btn-archive btn btn-info">Active</button>
<button type="button" data-client_id="{{ $client->id }}" class="btn-delete fa fa-trash btn btn-danger"></button>
my AJAX
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$(document).on('click','.btn-archive',function(){
var clientID=$(this).attr('data-client_id');
var url='/admin/clients/archTrash/'+clientID;
callAjax(url);
});
$(document).on('click','.btn-delete',function(){
var clientID=$(this).attr('data-client_id');
var url='/admin/clients/archTrashPermanent/'+clientID;
callAjax(url);
});
function callAjax(url){
$.ajax({
url:url,
dataType:'json',
type:'GET',
success:function(response){
console.log(response);
},
error:function(err){
console.log(err);
}
});
}
</script>
Table Structure
`
class Client extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
// Table Name
protected $table = 'clients';
// Primary Key
public $primaryKey = 'id';
// Timestamps
public $timestamps = true;`
This is what I am doing:
When creating the table, I attach a unique id (user-id in this case) to every row that can be deleted. This is how I do it in blade:
#foreach ($visitors as $visitor)
<tr class="data-user-id-{{$visitor->id}}">
<td class="text-left">
{{$visitor->name}}
</td>
<td class="text-left" data-original-value="11">
{{$visitor->email}}
</td>
<td class="text-left">
<a href="#" data-user-id="{{$visitor->id}}" class="btn btn-small btn-info btn-visitor-enable-disable">
Enable
</a>
</td>
<td class="text-left">
<a href="#" data-user-id="{{$visitor->id}}" class="btn btn-small btn-danger btn-visitor-delete">
X
</a>
</td>
</tr>
#endforeach
Then, in the success method of my .ajax call, I just select that row using the unique id of the row that was deleted and remove the row. This is how I do it.
$(".btn-visitor-delete").on('click',function(e) {
e.preventDefault();
const userId = $(this).attr('data-user-id');
var confirmation = confirm("Are you sure you want to delete this user?");
if (confirmation) {
$.ajax({
type:'GET',
url:'/dashboard/allwhitelistedusers/delete/' + userId,
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
// data:{user_id: userId},
success:function(data){
//Refresh the grid
$(".data-user-id-"+userId).remove();
alert(data.success);
},
error: function(e){
alert(e.error);
}
});
}
else{
//alert ('no');
return false;
}
});
if u want to delete a record in larval without refreshing the page using ajax so use the below code. I am using this code and its working fine
sending id to ajax in this button class which u can relate to yours id <button class="deleteRecord btn btn-danger" data-id="{{ $party->id }}" >Delete Record</button>
ajax codeis like this with sweet alert
$(".deleteRecord").click(function(){
var id = $(this).data("id");
var token = $("meta[name='csrf-token']").attr("content");
var parent = $(this).parent();
swal({
title: "Wait..!",
text: "Are You sure, You want to delete Party?",
icon: "warning",
buttons: true,
dangerMode: true,
}).then((willDelete) => {
if (willDelete) {
$.ajax({
url: "delete_party/"+id,
type: 'DELETE',
data: {
"id": id,
"_token": token,
},
success: function (){
parent.slideUp(300, function () {
parent.closest("tr").remove();
});
},
error: function() {
alert('error');
},
});
} else {
swal("Your Party is safe");
}
});
});
``
You are only doing half the work: Data is sent to the server and it seems everything is working as expected on that site. But then you want to "delete a client" (I assume you expect a table row to disappear) without reloading the page. You need to code this inside the success handler:
success: function(response) {
$('#client-data').remove();
console.log(response);
}
Note this example code will always remove the same element with the ID client-data. You'll probably need to use something like $(this).parent().remove(); as there seem to be multiple delete buttons on your page.

How to use a value imported from a database

Hey Everyone here is my question .
The code below gets data from my database and displays it both in an input field and a button. I want it to be in such a way that if i click the button it should get the value(which is imported from the db).But the problem i am facing is that all the inputs and buttons have the same ids so it only captures the value of the first button(or so i think). How can i make it in such a way that for every button i click it should have its own separate value.
<?php
$dbcon=mysqli_connect("localhost","root","");
mysqli_select_db($dbcon,"codex");
require('config/server.php');
?>
<table class="table table-striped">
<th>ID</th>
<?php
$view_users_query="select * from users";//select query for viewing
users.
$run=mysqli_query($dbcon,$view_users_query);//here run the sql
query.
while($row=mysqli_fetch_array($run))//while look to fetch the result
and store in a array $row.
{
?>
<!--here showing results in the table -->
<form id="loginForm" method="" action="" novalidate>
<tr>
<div class="panel2">
<main class="content">
<td><input name="hanis" id="hanis" type="text" value="<?php echo
$row['email']?>" autofocus /></td>
<td><button type="button" class="btn btn-success btn-block"
name="hanis" id="hanis" onclick="hanisdata()" value="<?php echo
$row['email']?>" ><?php echo $row['email']?></button><</td>
</main></div>
</div>
</div>
</form>
<?php } ?>
</tr>
<script type="text/javascript">
function hanisdata() {
var hanis=$("hanis").val();
alert(hanis);
// AJAX code to send data to php file.
$.ajax({
type: "POST",
url: "hanis.php",
data: {hanis:hanis},
dataType: "JSON",
success: function(data) {
$("#message").html(data);
$("p").addClass("alert alert-success");
},
error: function(err) {
alert(err);
}
});
}
</script>
NOTE :- Don't use same id for elements
You can get values by passing this with onclick function like onclick="hanisdata(this)"
Example
<button type="button" class="btn btn-success btn-block"
name="hanis" id="hanis" onclick="hanisdata(this)" value="<?php echo
$row['email']?>" ><?php echo $row['email']?></button>
Then you can get specific element in js and then can find parent and search for input field in that like below example.
JS CODE
<script type="text/javascript">
function hanisdata(el) {
var hanis=$(el).parent().find("input").val();
alert(hanis);
// AJAX code to send data to php file.
$.ajax({
type: "POST",
url: "hanis.php",
data: {hanis:hanis},
dataType: "JSON",
success: function(data) {
$("#message").html(data);
$("p").addClass("alert alert-success");
},
error: function(err) {
alert(err);
}
});
}
</script>

Getting different results from the same form in laravel

I'm trying to create an ajax form using laravel. The display is a table with names and next to the names are buttons enclosed by forms to do actions.
Here is the html:
<div style="margin-top: 100px;">
<h2>Character settings</h2>
<table class="table table-striped table-bordered table-hover">
<tr>
<th>Name</th>
<th>Map</th>
<th>Move</th>
</tr>
#foreach($chars as $char)
<tr>
<td>{{$char['name']}}</td>
<td>{{$char['map']}}</td>
<td>
{{Form::open(array('action' => 'UsersController#move', 'id' => 'mover'))}}
<input type="hidden" name="charID" id="charID" value="{{$char['id']}}" />
<button type="submit" class="btn btn-small btn-info">Move</button>
{{Form::close()}}
</td>
</tr>
#endforeach
</table>
Here is the javascript ajax processing:
$('#mover').on('submit', function(e){
e.preventDefault();
var $form = $( this ),
method = $form.attr( "method" );
$.ajax({
url: "{{action('UsersController#move')}}",
dataType: "json",
data: $('#charID').val(),
type: method,
success: function (response) {
console.log(reponse['test']);
}
});
});
Here is the controller:
public function move() {
return Response::json(array('test' => 'test'));
exit();
}
The table looks like:
Image here
If I click the first button for Sambte, it works and I see "test" in the console. But when I click the 2nd link it doesn't send as ajax and sends me to a new page with the json object as the content of that page so I see {"test":"test"} in the new page it brought me to.
I can't figure out what's wrong. Hopefully its a small error somewhere.
Thank you
ID's are unique, you need to use a class on the form instead.
'class' => 'mover'
Then just use the class instead of the ID in the selector
$('.mover')
Sidenote, the same needs to be done for the charID, here's how I'd tackle that:
class="charID"
then, in your submit handler:
data: $form.find('.charID').val()
$(document).on('submit','.mover', function(e){
e.preventDefault();
var $form = $( this ),
method = $form.attr( "method" );
$.ajax({
url: "{{action('UsersController#move')}}",
dataType: "json",
data: $(this).serialize(),
type: method,
success: function (response) {
console.log(reponse['test']);
}
});
});
change id=mover to class=mover

Laravel Passing ID from fetched data to AJAX

I'm at lost on what is the way to do this. So basically i got a multiple comment form like this :
#foreach($lists as $list)
//some views
<form class="commentForm">
<input type="text" class="commentBox" name="comment" />
<input type="submit" class="submitBtn" value="Comment" />
</form>
#endforeach
And i want to implement AJAX so that every time user comment something, the page won't reload. My current route for submitting the comment is :
Route::post('list/{listID}/comment', 'ListController#comment');
And i don't know how to pass that ID from the view to AJAX and then back to controller. I tried to obvious one, use 'list/{{ $list->id }}/comment' in the AJAX url, that didn't work. Also tried some other things but basically all for naught.
Thank you in advance !
EDIT : My AJAX code :
$(document).ready(function(){
$(document).on("submit", '.commentForm', function(e){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
var data = $(this).serialize();
var me= this;
$.ajax({
type: 'POST',
url: 'posts/{{ $auction->id }}/comment',
data: data,
datatype: 'JSON',
success:function(data){
console.log(data);
},
error:function(data){
console.log(data);
}
});
return false;
})
});
I just console.log-ing the outputs for now to see whether it works not.
In laravel, they use blade templating. I dont know where you put your ajax code, but these bracket: {{ }}, {!! !!} only will be considered as templating when you use the extension .blade.php.
In laravel you can use .php under resource/views as the html template, but the one inside {{ }}, {!! !!}, and other blade syntax will be treated as normal text instead of being interpreted again. If you need, usually i will make the layout will be something like this:
<html>
<head>
#yield("sytles")
#yield("additionalstyles")
#yield("includestyles")
................//as many as you need
</head>
<body>
<div>#yield("content")</div>//content here
#yield("scripts")
#yield("additionalscripts")
#yield("includescripts")
................//as many as you need
</body>
</html>
and then in the view, when i need to make ajax request, i will enclose it inside the #section("script") #stop or whichever the yield that haven't been used yet, so for example the view part of your code maybe will be like this after using this template:
#extends("layout")
#section("content")
#foreach($lists as $list)
//some views
<form class="commentForm">
<input type="text" class="commentBox" name="comment" />
<input type="submit" class="submitBtn" value="Comment" />
</form>
#endforeach
#stop
#section("additionalscript")
<script>
$(document).ready(function(){
$(document).on("submit", '.commentForm', function(e){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
var data = $(this).serialize();
var me= this;
$.ajax({
type: 'POST',
url: 'posts/{{ $auction->id }}/comment',
data: data,
datatype: 'JSON',
success:function(data){
console.log(data);
},
error:function(data){
console.log(data);
}
});
return false;
})
});
</script>
#stop
In this way, your
url: 'posts/{{ $auction->id }}/comment',
will going to be rendered as something like
url: 'posts/hansishandsome/comment',
Hope this help
I recommend using jQuery's .data() feature, so in the foreach loop you do this:
<form class="commentForm" data-id="{{$list->id}}">
<input type="text" class="commentBox" name="comment" />
<input type="submit" class="submitBtn" value="Comment" />
</form>
Then one listener to rule them all:
$(document).on("submit", '.commentForm', function(e){
e.preventDefault();
var comment_id = $(this).data('id');
console.log('comment id = ',comment_id);
$.ajax({
type: 'POST',
url: 'posts/' + comment_id + '/comment',
//etc...
});
You can do following steps:
Add one hidden field with value as Listid in form like:
<input type="hidden" id="listId" value="{{$list->id}}" />
And then you can use it in ajax call like:
$listId = $("#listId").val();
These are the following ways you can do it
Create a hidden input
<input type="hidden" id="listid" name="listid" value="{{ $list->id }}">
and read the value through JQuery
var listid = $('#listid').val();
Create a JSON object and read it in your
<script>
var list = {
id : {{ $list->id }} //you can also add other variables in the object
}
</script>
And in your js file use the list object
NOTE: the list object must initialized before you run your script
$.post('list/' + list.id + '/comment', data);

Categories