Passing data to a bootstrap modal from Laravel - php

Wonder if someone can help me with this one. I am a complete newbie with JS and JQuery.
I want to avoid accidents with deleting posts in my blog, so I want to have it so that when I hit delete it will pop up a modal to confirm I do want to delete the post and then do it or not.
I have added the following code.
<!-- Button trigger modal to delete post -->
<button type="button" class="btn btn-default btn-xs" data-toggle="modal" data-target="#deletePost">
Delete
</button>
<!-- Modal -->
<div class="modal fade" id="deletePost" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Delete Blog Post</h4>
</div>
<div class="modal-body">
<p>You are about to delete a blog post, are you sure all that effort is to be sent to the unrecoverable trash can?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default pull-left" data-dismiss="modal">OMG, NO!!!</button>
<form action="/blog/{{ $post->id }}" method="POST">
{{ csrf_field() }}
{{ method_field('DELETE') }}
<button type="submit" class="pull-right btn btn-danger">Delete it!</button>
</form>
</div>
</div>
</div>
</div>
Now all that works fine, all I now want to do is that when I click the "delete it!" button it will do just that.
It all works apart from deleting the right post, I want to pass
{{ $post->id }}
to the modal so that it will send the post id to the controller.
My question is how I pass the id above to the modal? I have read a lot of examples and they are all so different so thought it better to get some views.
Thanks!

I would very much recommend using SweetAlert plugin, it is visually compatible with Twitter Bootstrap and much more pleasant to use.
This is a piece of code for multilingual, model-independant delete function:
$('body').on('click', 'sweet-delete', function (e) {
e.preventDefault();
var id = $(this).data('id');
var model = $(this).data('model');
swal({
title: lang.confirm_please,
text: lang.delete_warning,
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: lang.delete_button,
closeOnConfirm: false,
showLoaderOnConfirm: true,
}, function(){
$.post('/'+model+'/'+id, {_method: 'DELETE'}, function(data){
swal({
title: lang.delete_title,
text: lang.delete_success,
type: "success",
timer: 5000
}, function(){
window.location.href = '/'+model;
});
});
});
})
And in you view:
<button data-id="{{$post->id}}" data-model="blog" class="pull-right btn btn-danger sweet-delete">#lang('app.delete')</button>
I have to mention that in order to attach CSRF token to my ajax forms I use:
$.ajaxSetup({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}
});
in my app.js, and
<meta name="csrf-token" content="{{csrf_token()}}">
in my main layout file.

To pass the post ID to the modal form, it should be inserted in the modal using jQuery.
Button:
<button type="button" class="btn btn-default btn-xs delete-post" data-post-id="{{ $post->id }}">Delete</button>
Note: we will trigger the modal using the following, so we can also insert the ID.
jQuery:
$(document).ready(function() {
var modalObj = $('#deletePost');
$('.delete-post').click(function(e) {
var postId = $(this).data('post-id');
modalObj.find('form').attr('action', '/blog/' + postId);
modalObj.modal('show');
});
});
In this case, the action attribute is set dynamically, according to the relevant post id.

Related

Cannot delete a row in Datatables after making it a delete request

I'm using DataTables in Laravel, and I want to delete a row from the database. It used to work when I did it as a get request in the route, but since I changed it to the delete request and put the csrf and method under the form, it stopped working. I receive - Data Not Deleted error. What can be a reason of that happening? Button that I receive from the index controller:
$button = ' <button type="button" name="edit" id="'.$data->id.'" class="delete btn btn-danger btn-sm"> <i class="fas fa-fw fa-trash"></i> Delete</button>';
HTML form that appears when a delete button is clicked:
<div class="modal fade" id="confirmModal" tabindex="-1" aria-labelledby="ModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form method="post" id="sample_form" class="form-horizontal">
#csrf
#method('DELETE')
<div class="modal-header">
<h5 class="modal-title" id="ModalLabel">Confirmation</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<h4 align="center" style="margin:0;">Are you sure you want to remove this data?</h4>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" name="ok_button" id="ok_button" class="btn btn-danger">OK</button>
</div>
</form>
</div>
</div>
</div>
Script:
var employee_id;
$(document).on('click', '.delete', function(){
employee_id = $(this).attr('id');
$('#confirmModal').modal('show');
});
$('#ok_button').click(function(){
$.ajax({
url:"/admin/employees/destroy/"+employee_id,
beforeSend:function(){
$('#ok_button').text('Deleting...');
},
success:function(data)
{
setTimeout(function(){
$('#confirmModal').modal('hide');
$('#employee_table').DataTable().ajax.reload();
alert('Data Deleted');
}, 2000);
},
error: function(xhr, status, error) {
setTimeout(function(){
$('#confirmModal').modal('hide');
$('#employee_table').DataTable().ajax.reload();
alert('Data Not Deleted');
}, 2000);
},
})
});
});
Route:
Route::delete('/admin/employees/destroy/{id}', [EmployeeController::class, 'destroy']);
Controller function:
public function destroy($id)
{
$data = Employee::findOrFail($id);
$data->delete();
}
In your route you are using delete method, but in ajax call you have not mentioned the method, so the error is 405 method not allowed,
Try adding type: delete in ajax. something like this:
$.ajax({
type: 'DELETE',
url:"/admin/employees/destroy/"+employee_id,
To solve the problem I had to put csrf inside the meta:
<meta name="csrf-token" content="{{ csrf_token() }}" />
And use this at the beginning of the script:
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>

How do I do a reset of the Bootstrap modal window without reloading the page ? Using PHP , jQuery, AJAX

I have a comment system. The user can report a bad comment (jquery and AJAX). When there are several comments for the same post the Bootstrap modal window retains the message from the previous report.
How do I do a reset of the modal window without reloading the page?
post.php
<button type="button" id="showModal" class="btn btn-primary btn-sm reporting" data-comment-id = "<?= $comment->getId() ?>" data-toggle="modal" data-target="#reportModal"></button>
<div class="modal fade" id="reportModal" tabindex="-1" role="dialog" aria-labelledby="title-report" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="title-report">Confirm reporting</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary submit-reporting">Validate</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
<input type="hidden" name="id" id="commentId" value="">
</div>
</div>
report.js
$(document).ready(function(){
$('.reporting').click(function(e) {
e.preventDefault();
$('#commentId').val($(this).data('comment-id'));
});
$('.submit-reporting').click(function(e) {
e.preventDefault();
var commentId = $('#commentId').val();
$.ajax({
url: 'post/moderateComment/' + commentId,
success: function(){
$(".modal-body").html("<p>The report has been forwarded!</p>");
$('.submit-reporting').attr("disabled", "disabled");
$('[data-comment-id = "'+commentId+'"]').hide();
}
});
});
});
I think what you are looking for is to have a modal with it's initial state? If that is so, you can do it by tweaking your modal when it is opened and resetting the elements that you want. So in your javascript, you should have something like:
$(document).ready(function(){
$('.reporting').click(function(e) {
e.preventDefault();
//Clean your message here*** with something like
//$('.elementWHereMessageIs').empty(); //Is faster than text('') or html('')
$(".modal-body").empty(); // I don't know if this is the message you want to empty?
$('#commentId').val($(this).data('comment-id'));
});
$('.submit-reporting').click(function(e) {
e.preventDefault();
var commentId = $('#commentId').val();
$.ajax({
url: 'post/moderateComment/' + commentId,
success: function(){
$(".modal-body").html("<p>The report has been forwarded!</p>");
$('.submit-reporting').attr("disabled", "disabled");
$('[data-comment-id = "'+commentId+'"]').hide();
}
});
});
});
Hope this helps!
Leo.

How to update data using modal with ajax, php and mysql?

I want to update data using modal with ajax in PHP. I am beginer, plz tell me where is my mistake .
HTML Code
<button type="submit" class="btn btn-success" data-toggle="modal" data-cphone='.$row['country_phon'].' data-cname='.$row['country_name'].' >Update</button>';
<div id="myModal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Update Country</h4>
</div>
<form action="" method="post">
<div class="modal-body">
<input type="text" id="cn" name="pcountry">
</div>
<div class="modal-body">
<input type="text" id="cph" name="pphone">
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary updt" name="updatecountry" >Save</button>
JS Code: Here when I click on Button, modal appears with the values fetched from database with the help of jquery.
<script>
$(document).ready(function(){
$(".btn").click(function(){
var cphone =$(this).data('cphone');
var cname = $(this).data('cname');
$("#cph").val(cphone);
$("#cn").val(cname);
$("#myModal").modal('show');
});
});</script>
JS code : This is ajax code . I want to update the text of textbox.
<script>
$(".updt").click(function(e){
e.preventDefault();
var cnt = $("#myModal").find("input[name='pcountry']").val();
var cp = $("#myModal").find("input[name='pphone']").val();
$.ajax({
dataType: 'json',
type:'POST',
url: 'test.php',
data:{pcountry:cnt, pphone:cp},
})
)};
</script></div>
PHP Code :
<?php
if(isset($_POST['updatecountry']))
{$country1 = $_POST['pcountry'];
$phone1 = $_POST['pphone'];
echo $country1;
echo $phone1;
echo "Updated Successfully";
mysqli_query($conn,"update country set country_name='$country1' , country_phon='$phone1' where country_id=18");
mysqli_close($conn);
}?>
On view btn class use for update and save. I suggest you please use different class name or id.
<button type="submit" class="form_update btn btn-success" data-toggle="modal" data-cphone='.$row['country_phon'].' data-cname='.$row['country_name'].' >Update</button>';
JS changes
<script>
$(document).ready(function(){
$(".form_update").click(function(){
var cphone = $(this).attr("data-phone");
var cname = $(this).attr("data-cname");
$("#cph").val(cphone);
$("#cn").val(cname);
$("#myModal").modal('show');
});
});
</script>
Hope this code is workinf fine.

Updating the query on the other page and set the button disabled

I have a question regarding ajax and modal. What I need to do is, when user click submit of the button, it should set the button disabled and sending the values to the other page to update the database. But my approach is using modal.
My modal code is like this,
<div class="modal fade" id="qcRejectModal" 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="myModalLabel">QC <font color="CC0000"><b>REJECT</b></font> Confirmation Window</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<div class="form-group">
This is the confirmation window to PASS all the Quality Control for, <br/><br/>
PROJECT : <b>'.$row['PROJECT_NAME'].'</b>
HEADMARK : <b>'.$row['HEAD_MARK'].'</b>
ID : <b>'.$row['ID'].'
</div>
</div>
</div><br/>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<textarea class="form-control" placeholder="Reason for rejection" rows="2" name="rejectionreason" id="rejectionreason" required></textarea>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" name="rejectbutton" id="rejectbutton" class="btn btn-danger">Confirm REJECT!</button>
</div>
</div>
</div>
</div>
</div>
So in this code when user click the button,
echo "<input type='hidden' data_project='$row[PROJECT_NAME]' data_headmark='$row[HEAD_MARK]' data_id='$row[ID]'></input>";
echo '<button type="button" name="qcreject" id="qcreject" class="btn btn-primary btn-danger btn- lg btn-block" data-toggle="modal" data-target="#qcRejectModal">
<span style="font-size:35px"> '.$row['PROJECT_NAME'].' / <b>'.$_POST ["hm"].'</b>/'.$row['ID'].' ~ FAIL</span></button>';
modal code is executed and showed and waiting for the user to input the comment in the textfield and when user click REJECT button, it should pass
$row['PROJECT_NAME'], $row['HEAD_MARK'], $row['ID'] and the textfield value (#rejectionreason)into the processclass.php.
And on the processclass.php, those variables will be used to update the database with SQL query.
This is the snippet of my ajax.
$('.rejectbutton').click(function() {
$.ajax({
url: 'processclass.php',
type: 'POST',
data: ,
success: function (result) {
alert("Your data has been submitted");
}
});
});
I am having problem with executing on the process class. that means passing those values to the processclass.php.
$('.rejectbutton').click(function() {
$(this).attr('disabled','disabled');
$.ajax({
url: 'processclass.php',
type: 'POST',
data: {param_name: '<?php echo $param_value ?>'},
success: function (result) {
alert("Your data has been submitted");
},
complete: function(){
$(this).removeAttr('disabled');
}
});
});

bootstrap handling a ajax form submission

I have been trying to get this form to load for a couple days now, but all I can get is the form to submit to a page (not what I want, I want the form to submit and then close the modal and then put a success message from news.php into the div "thanks" holder).
Can anyone spot the issue I am having where it will one load the "news.php" page?
<div id="thanks"></div>
<div class="modal fade" id="newsModal" tabindex="-1" role="dialog" aria-labelledby="newsModalLabel" 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="newsModalLabel">Add a News Post</h4>
</div>
<div class="modal-body">
<form class="addNew" role="form" method="POST" action="news.php">
<div class="form-group">
<input type="text" name="title" class="form-control" id="title" placeholder="Enter title here...">
</div>
<div class="form-group">
<textarea class="form-control" name="message" rows="7" placeholder="Enter news post here..."></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary" id="addNews">Add News Post</button>
</form>
</div>
</div>
</div>
</div>
and the javascript is:
<script type="text/javascript">
$(document).ready(function () {
$("button#addNews").click(function(){
$.ajax({
type: "POST",
url: "news.php",
data: $('form.addNew').serialize(),
success: function(msg){
$("#thanks").html(msg) //hide button and show thank you
$("#newsModal").modal('hide');
},
error: function(){
alert("failure");
}
});
});
});
</script>
You didn't pass the event object to your click binding :
<script type="text/javascript">
$(document).ready(function (e) { // pass the event object
$("button#addNews").click(function(){
e.preventDefault(); // disable the POST of the form by the submit button
$.ajax({
type: "POST",
url: "news.php",
data: $('form.addNew').serialize(),
success: function(msg){
$("#thanks").html(msg) //hide button and show thank you
$("#newsModal").modal('hide');
},
error: function(){
alert("failure");
}
});
});
});
Oops, I forgot the BootPly of my test.
I just replaced your POST request to a GET one, I don't know how to make POST request inside BootPly.
button#addNews is the submit button for the form, also it's click event is binded with an ajax call. When it is clicked, ajax process begins to execute while the form is being submitted.
You need to remove <form... start & end tags.

Categories