I want to delete specific rows in mysql by jquery. It works on the first row, but in the second row, nothing happens.
This is my HTML code:
<td><p data-placement="top" data-toggle="tooltip" title="Delete">
<button id="dele_com" class="btn btn-danger btn-xs" name="<?php echo $rows['companyID']; ?>">
<span class="icon-trash"></span>
</button></p>
</td>
and this is my jquery code:
$("#dele_com").on("click", function(event) {
var show_id = this.name;
alert(show_id);
bootbox.dialog({
message: "Are you sure you want to Delete this account ?",
title: "<i class='icon-trash'></i> Delete !",
buttons: {
success: {
label: "No",
className: "btn-success",
callback: function() {
$('.bootbox').modal('hide');
}
},
danger: {
label: "Delete!",
className: "btn-danger",
callback: function() {
$.post('update_delete.php', { 'pid1':pid1 })
.done(function(response){
window.location.href= "modification.php";
})
.fail(function(){
bootbox.alert('Something Went Wrog ....');
})
}
}
}
});
});
Here you have specified the id #dele_com and that will be the same for every row. So when you click on the delete button it will find the first id of your table and performs click.
You have to use class selector instead of id then it will work
Related
I got some troubles when using swal to confirm delete, I do not know how to make it work
here is my blade view file:
<form action="{{ route('user.destroy', $us->id)}}" method="post">
#method('DELETE')
#csrf
<input class="btn btn-danger" type="submit" value="Delete" />
</form>
and the script using swal
<script>
//== Class definition
var SweetAlert2Demo = function() {
//== Demos
var initDemos = function() {
$('.btn-danger').click(function(e) {
e.preventDefault();
swal({
title: 'Are you sure?',
text: "You won't be able to revert this!",
type: 'warning',
buttons:{
confirm: {
text : 'Yes, delete it!',
className : 'btn btn-success'
},
cancel: {
visible: true,
className: 'btn btn-danger'
}
}
}).then((Delete) => {
if (!Delete) {
e.preventDefault();
}
});
});
};
return {
//== Init
init: function() {
initDemos();
},
};
}();
//== Class Initialization
jQuery(document).ready(function() {
SweetAlert2Demo.init();
});
</script>
the version of swal is https://sweetalert.js.org not https://sweetalert2.github.io/
And I'm using route resource on laravel 5.8
thanks you!
Update in case of Loops
You should give an id to your form and then in the swal callback submit the form by using the ID
<form action="{{ route('user.destroy', $us->id)}}" method="post" id="yourFormId">
Your JS Click button is almost same. Just some small change in the Swal JS Callback Method
$('.btn-danger').click(function(e) {
var $form = $(this).closest("form"); //Get the form here.
e.preventDefault();
swal({
title: 'Are you sure?',
text: "You won't be able to revert this!",
type: 'warning',
buttons:{
confirm: {
text : 'Yes, delete it!',
className : 'btn btn-success'
},
cancel: {
visible: true,
className: 'btn btn-danger'
}
}
}).then((Delete) => {
console.log(Delete); //This will be true when delete is clicked
if (Delete) {
$form.submit(); //Submit your Form Here.
//$('#yourFormId').submit(); //Use same Form Id to submit the Form.
}
});
});
Use GET method instead of POST.
And no need to use button or combine anything.
Try this example,which always works with my all projects.
As
Use anchor tag, Not button
<a class="btn btn-action text-danger" title="Delete" data-toggle="tooltip" onclick="deletefunction({{$your_id}})"><i class="fa fa-trash"></i></a>
Add Script As,
<script>
var deletefunction = function(id){
swal({
title: "Are you sure you want to Delete this?",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes",
closeOnConfirm: false,
preConfirm: function(result) {
window.location.href = '{{url('/your_route/delete')}}/'+id;
},
allowOutsideClick: false
});
};
</script>
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.
In blade I have this code:
#foreach ($employees as $key => $employee)
<tr id="{{$employee->id}}">
<td class="visibleemployee tdcenter">
<form action="{{route('admin.employees.cambiarVisible',$employee->id)}}">
<button type="button" id="buttonchangevisible" data-id="{{$employee->id}}">
#if ($employee->public == '1')
<i class="fa fa-check" aria-hidden="true" id="margindataemployee" class="cambiarsiporno"></i>
#else
<i class="fa fa-times" aria-hidden="true" id="margindataemployee"></i>
#endif
</button>
<input type="hidden" name="_token" value="{{Session::token()}}">
</form>
</td>
</tr>
#endforeach
When I click the bottom the Ajax function is executed:
$("#buttonchangevisible").click(function(e){
e.preventDefault();
var button = $(this);
var id = button.data('id');
var formData = new FormData($(this)[0]);
$.ajax({
url:'employee/cambiarVisible/' + id,
type: 'PUT',
data: formData,
success: function() {
location.reload();
},
cache: false,
contentType: false,
processData: false
});
return false;
});
And call to the next method:
public function cambiarVisible(Request $request, $id)
{
$employee = Worker::find($id);
if ($employee->public = 0){
DB::table('workers')->where('id',$id)
->first()
->$employee->public = 1;
}
else{
$employee->public = 0;
}
$employee->save();
}
Now don't appear any error, if I click in first row, make the call but don't the update of visible.
But if I click in other row, don't make the call.
I wrote a similar piece of code.
I generated the form dynamically, then called some JavaScript/jQuery.
Code to generate the button:
<button class="btn btn-danger btn-block deleteUserBtn" data-name="{{ $user->name }}" data-id="{{ $user->id }}" data-type="delete" onclick="return false;"><i class="glyphicon glyphicon-trash"></i> Delete</button>
Then using the following code, I executed the ajax call. The reason the click event is attached to the body is because there are multiple delete buttons (this was for an user overview with multiple delete buttons, one for every user). And these buttons can be generated with jQuery, the click event will not fire if you bind to the buttons.
$('body').on('click', '.deleteUserBtn', function() {
var button = $(this) // Button that triggered the event
var id = button.data('id');
var name = button.data('name');
var csrf = $('input[name=_token]').val(); // This token is already on the page, you need a token to prevent csrf
if( confirm('Are you sure you want to delete: ' + name + '?') ) {
var url = "{{ route('overview.users.destroy', ':id') }}";
url = url.replace(':id', id);
$.ajax({
method: "DELETE",
url: url,
data: {
'id': id,
'_token': csrf
},
}).done(function(response) {
// Check if it is successful
if(response == 'deleted') {
// Reload page
location.reload();
} else {
alert('error');
console.log(response);
}
}).fail(function(response) {
alert('error 2');
console.log(response);
});
}
});
As you can see I just passed the id as a parameter.
In your case, to update the user, you can just use the following piece of code:
public function cambiarVisible(Request $request, $id)
{
$employee = Worker::findOrFail($id);
$employee->public = ($employee->public == 1) ? 0 : 1;
$employee->save();
}
Looks like your form has a ajax submit which is using employee/cambiarVisible/{id} as URL. since the id wildcard is supposed to be a php variable (cannot see the variable in JS), it's not being passed to the controller.
Try something like
var id = {!! json_encode($employee->id) !!};
Then change the url as
url:'employee/cambiarVisible/' + id,
I want to remove selected div part by click on cancel button php code
while($fetch_user_info= mysqli_fetch_assoc($query_client))
{
<div class="col-sm-12 m-t-20 insight_box">
<button type="button" class="btn btn-default btn-sm cancel_insights" value="<?php echo $c_id;?>">Cancel</button>
<button type="button" class="btn btn-info btn-sm " onclick="window.open('<?php echo $url.'?pan='.$jh1_pan ?>', '_blank')">Yes, On board now!</button>
</div>
}
?>
Jquery :
$('.cancel_insights').click(function() {
var c_id = $(this).val();
$.post('url', {
'c_id': c_id,
'action': 'action'
}, function(data, status) {
if (data == 'true') {
$(this).find('.insight_box').fadeOut();
}
});
});
change
$(this).find('.insight_box').fadeOut();
into this
$(this).parent().fadeOut();
You could add an event so when the button is clicked it gets its parent and removes it, like so
$(".cancel_insights").click(function() {
$(this).parent().remove();
});
I have 3 steps to do:
Send some datas via AJAX to a PHP page
Retrieve results and show to user a button with popover which contains a form to save name of user search
Send this form in other PHP page via other AJAX
Points 1 and 2 work fine.
I put popover function in 'complete' section of ajax because popover is created only after results are retrieved.
For point 3, i am unable to catch last form with on.submit. When i click on submit button, it sends form (reload my page).
Here is my code:
HTML part:
<body>
<div class="row" id="results"></div>
</body>
JS part:
/* popover form for save search */
var search_box = '<div id="popover-content" class="hide">'+
'<form id="searchForm" class="form-inline" role="form">'+
'<div class="form-group has-warning">'+
'<input placeholder="Name" class="form-control" maxlength="50" type="text"> '+
'<button type="submit" class="btn btn-warning"><i class="fa fa-check"></i></button>'+
'</div>'+
'</form>'+
'</div>';
/* function to retrieve results and show button with popover */
function searchresults() {
if(select_data !== ''){
$.ajax({
type: "POST",
dataType: 'json',
url: "search.php",
data: { q: select_data },
cache: false,
success: function(data) {
if($.isPlainObject(data) && data.state === 200){
// here is code to retrieve results...
// show button with popover and form
saveButton ='<button type="button" class="btn btn-outline btn-warning btn-lg" data-toggle="popover" data-placement="auto top" data-title="Enter name for your search"><i class="fa fa-star"></i> Save selection</button>'+search_box;
$("div#results").html(saveButton);
}
},
complete: function (jqXHR, status) {
$("[data-toggle=popover]").popover({
html: true,
content: function() {
return $('#popover-content').html();
}
});
/* ******** PART DOES NOT WORK ******** */
$("#searchForm").on('submit', function(e) {
e.preventDefault();
alert('passed');
/* code ajax here */
return false;
});
}
});
}return false;
}
How to correct this?
Try to add $(document) .... Let me know if it works I didnt test
$(document).on('submit', 'form#yourFormID', function(e) {
e.preventDefault();
alert('passed');
/* code ajax here */
return false;
});