jquery ajax pass variable from link - javascript

I'm trying to pass a variable from my link to ajax, but I cannot do so.
This is the code I'm working on:
<script type="text/javascript">
$(function(){
$(".btn-show-modal").click(function(e){
e.preventDefault();
$("#dialog-example").modal('show');
});
$("#btn-delete").click(function(e) {
var id = $(this).attr('data-id');
$.ajax({
type:"POST",
data: { id : id },
url:"delete-project.php",
success:function(result){
$("#dialog-example").modal('hide');
}
});
});
});
</script>
<table class="table table-bordered">
<tr>
<td>Project Code</td>
<td>Description</td>
</tr>
<?php
$stmt2 = $conn->prepare( "SELECT project_code, description FROM tblprojects" );
$stmt2->execute();
for($i=0; $row2 = $stmt2->fetch(); $i++){
$project = $row2['project_code'];
$desc = $row2['description'];?>
<tr class="record" id="record-">
<td>
<?php echo $project; ?>
</td>
<td><?php echo $desc; ?></td>
<td>
<a href="update-project.php?code=<?php echo $project; ?>" title="Update record">
<i class="icon-edit icon-white"></i>
</a>
</td>
<td>
<a href="#" data-id="<?php echo $project; ?>" id="<?php echo $project; ?>" class="btn-show-modal" data-toggle="modal" title="Delete record">
<i class="icon-trash icon-white"></i>
</a>
</td>
<div class="modal hide fade" id="dialog-example">
<div class="modal-header">
<h5>Confirm Delete</h5>
</div>
<div class="modal-body">
<p class="modaltext">Are you sure you want to delete this record?</p>
</div>
<div class="modal-footer">
<a href="#" data-dismiss="modal" class="btn btn-info">No<a>
<a data-id="<?php echo $project; ?>" class="btn btn-danger" id="btn-delete">Yes<a>
</div>
</div>
</tr>
<?php
}
?>
</table>
I have a table where it has a delete column, if it is clicked a confirmation modal will appear that has 2 options yes or no. If yes is clicked, I need to delete that record and dismiss the modal, display the result without refreshing the page. How can I do that? I tried using ajax, I don't know if I am using it correctly. Your help will greatly appreciated. Thanks.

IDs must be unique in your DOM.
You have multiple links with id="btn-delete". That is the reason your code is not working
Change it to class, as below
In your markup:
<a data-id="<?php echo $project; ?>" class="btn btn-danger btn-delete">Yes<a>
And in your jQuery:
$(".btn-delete").click(...);

IDs must be unique Change to class instead and use $(this).data("id")
You also likely want to hide the deleted data from the page too
<a data-id="<?php echo $project; ?>"
class="btn btn-danger btn-delete">Yes<a>
$(".btn-delete").on("click",function(e) {
e.preventDefault(); // cancel the link
var id = $(this).data('id');
$.ajax({
type:"POST",
data: { id : id },
url:"delete-project.php",
success:function(result){
$(this).closest("tr").remove(); // remove the row from view
$("#dialog-example").modal('hide');
}
});
});
Lastly I suggest you have only ONE dialog on the page and pass the ID to delete and ID or the row to it
Passing data to a jQuery UI Dialog

You're just hiding the modal when the delete success event is executed. You have to remove the line from the table too.
You can remove it like this :
$(this).parents('tr').remove();
UPDATE :
The following code was tested and is working. If you still have error, you should open firebug and report the error message. You have some basic syntax problem or errors in your code, I corrected some in this solution, but you should look at tutorials or documentations to learn basic and good practice to provide a good structured code.
Just replace the html table lines (tr) below with your php loop to generate the lines.
<!-- place your modal out of a table. In a table you have tr and td, no div.
By the way you just need 1 modal for all rows -->
<div class="modal hide fade" id="dialog-example">
<div class="modal-header">
<h5>Confirm Delete</h5>
</div>
<div class="modal-body">
<p class="modaltext">Are you sure you want to delete this record?</p>
</div>
<div class="modal-footer">
No
Yes
</div>
</div>
<table class="table table-bordered">
<tr>
<th>Project Code</th>
<th>Description</th>
<th>Actions</th>
</tr>
<tr class="record" id="record-1">
<td>
project1
</td>
<td>description</td>
<td>
<a href="update-project.php?code=proj1" title="Update record">
<i class="icon-edit icon-white"></i>
</a>
<a href="#" data-id="proj1" id="proj1" class="btn-show-modal" data-toggle="modal" title="Delete record">
<i class="icon-trash icon-white"></i>
</a>
</td>
</tr>
<tr class="record" id="record-2">
<td>
project2
</td>
<td>description</td>
<td>
<a href="update-project.php?code=proj2" title="Update record">
<i class="icon-edit icon-white"></i>
</a>
<a href="#" data-id="proj2" id="proj2" class="btn-show-modal" data-toggle="modal" title="Delete record">
<i class="icon-trash icon-white"></i>
</a>
</td>
</tr>
</table>
<script>
$(function(){
$(".btn-show-modal").click(function(e){
e.preventDefault();
var btnDelete = $("#btn-delete");
//show the modal
$("#dialog-example").modal('show');
//save the id to delete if confirmed
var id=$(this).attr('data-id');
btnDelete.data('toRemove', id);
return false;
});
//action when clicking YES
$("#btn-delete").click(function(e) {
var id = $("#btn-delete").data('toRemove');
alert(id);
$.ajax({
type:"POST",
data: { id : id },
url:"delete-project.php",
success:function(result){
//hide the modal
var modal = $("#dialog-example");
modal.modal('hide');
var btnDelete = $("#btn-delete");
//remove the saved id
var id= btnDelete.data('toRemove');
//remove the row dynamically
$("#"+id).closest('tr').remove();
},
error:function( jqXHR, textStatus ) {
alert( "Request has failed! ; " + jqXHR.status + " / "+textStatus);
}
});
});
});
</script>

Related

How to delete a row from database with a Bootstrap Modal on html page?

I want to delete a row from the database with the modal for confirmation of deleting the row here is the part of the php I have
<div class="container col-sm col-md col-lg col-xl" id="header">
<table class="table table-bordered" id="myList">
<thead>
<tr>
<th>S.No</th>
<th>Name</th>
<th>Email</th>
<th>Rating</th>
<th>Review</th>
<th>Image</th>
<th>Suggestion</th>
<th>NPS</th>
<th>Delete</th>
</tr>
</thead>
<tbody class="table-warning" id="myList">
<?php
include 'database_conn.php'; // makes db connection
$sql = "SELECT feedbackID, name, email, rating, review, image, suggestion, nps
FROM feedback
ORDER BY feedbackID Desc";
$queryResult = $dbConn->query($sql);
// Check for and handle query failure
if($queryResult === false) {
echo "<p>Query failed: ".$dbConn->error."</p>\n";
exit;
}
// Otherwise fetch all the rows returned by the query one by one
else {
if ($queryResult->num_rows > 0) {
while ($rowObj = $queryResult->fetch_object()) {
echo "<tr>
<td>{$rowObj->feedbackID}</td>
<td>{$rowObj->name}</td>
<td>{$rowObj->email}</td>
<td>{$rowObj->rating}</td>
<td>{$rowObj->review}</td>
<td><img width='350px' height='200px' src='data:image;base64,{$rowObj->image}'/></td>
<td>{$rowObj->suggestion}</td>
<td>{$rowObj->nps}</td>
<td>
<button type='button' class='btn btn-danger' data-bs-toggle='modal' data-bs-target='#deleteModal' name='Delete' id='delete'>
<i class='fa fa-trash'></i> Delete</button>
<!-- Modal --->
<div class='modal fade' id='#deleteModal' tabindex='-1' aria-labelledby='deleteModalLabel' aria-hidden='true'>
<div class='modal-dialog'>
<div class='modal-content'>
<div class='modal-header'>
<h5 class='modal-title' id='deleteModalLabel'>Delete Confirmation</h5>
<button type='button' class='btn-close' data-bs-dismiss='modal' aria-label='Close'></button>
</div>
<div class='modal-body'>
Do you really want to delete this feedback?
</div>
<div class='modal-footer'>
<button type='button' class='btn btn-secondary' data-bs-dismiss='modal'>No</button>
<button type='button' class='btn btn-danger' href=delete.php?id={$rowObj->feedbackID} >Delete</button>
</div>
</div>
</div>
</div>
</td>
</tr>
";
}
}
}
?>
</tbody>
</table>
</div>
The delete button is not responding to execute the delete row command. Before adding modal I have the following code for the delete button, it worked fine but when I added modal it's not responding:
<td><a class='btn btn-danger' href=delete.php?id={$rowObj->feedbackID} style='vertical-align:middle' id='delete'>Delete</a></td>
Hope I gave the enough info to solve the issue, TIA

How can I make an accept button for each row in the table?

I want to make an accept button where when I press the accept button another column is shown, it worked fine in the first row of the table, but the other rows did not work.
Here is My HTML and PHP code:
<tbody>
<?php
$sql = "SELECT * FROM appointments INNER JOIN patients ON appointments.patientID =patients.patientID WHERE docID='$doctorId'";
$stmt = $conn->prepare($sql);
$stmt->execute();
$i=0;
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$i++;
extract($row);
echo"<tr>
<td >$i</td>
<td>{$patientFName} {$patientLName}</td>
<td>{$AppStart}</td>
<td>{$AppEnd}</td>
<td id='refuseAccept' style='display:block;'>
<button type='button' class='btn btn-outline-danger'>refuse</button>
<button type='button' class='btn btn-outline-success m-2 acceptPpomentDoc' >accept</button>
</td>
<td id='showOptions' style='display:none; class='m-2' >
<a href='#' title='view Details' class='text-success p-2 addappoment' > <i class='fas fa-calendar-check'></i></a>
<a href='#' title='Edit' class='text-primary p-2 editBtn' ><i class='fas fa-user-edit'></i> </a>
<a href='#' title='Delete' class='text-danger p2 deleteBtn' ><i class='fas fa-user-times'></i> </a>
</td>
</tr>
";
}
?>
</tbody>
and here is Javascript:
$(document).on('click','.acceptPpomentDoc', function (){
document.getElementById('showOptions').style.display = "block";
document.getElementById('refuseAccept').style.display = "none";
});
Don't use the same id multiple times. Instead use a class name or other attribute. You can reference the target div tags using relative paths, like:
$(document).on('click', '.acceptPpomentDoc', function() {
// $(this) references the item clicked, in this case the accept button
$(this).closest('tr').find('.showOptions').show();
// find the containing <tr>, then from there find the div with class name showOptions and set display:block
$(this).closest('tr').find('.refuseAccept').hide();
// find the containing <tr>, then from there find the div with class name refuseAccept and set display:none
});
$(document).on('click', '.acceptPpomentDoc', function() {
$(this).closest('tr').find('.showOptions').show();
$(this).closest('tr').find('.refuseAccept').hide();
});
.showOptions {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>$i</td>
<td>{$patientFName} {$patientLName}</td>
<td>{$AppStart}</td>
<td>{$AppEnd}</td>
<td class='refuseAccept'>
<button type='button' class='btn btn-outline-danger'>refuse</button>
<button type='button' class='btn btn-outline-success m-2 acceptPpomentDoc'>accept</button>
</td>
<td class='showOptions m-2'><strong>ACCEPTED
<a href='#' title='view Details' class='text-success p-2 addappoment'> <i class='fas fa-calendar-check'></i></a>
<a href='#' title='Edit' class='text-primary p-2 editBtn'><i class='fas fa-user-edit'></i> </a>
<a href='#' title='Delete' class='text-danger p2 deleteBtn'><i class='fas fa-user-times'></i> </a>
</td>
</tr>
</table>

Datatables does not activate

I am using JavaScript to load a file into a div. Which contains a table that I want to activate as DataTable
panel.js:
document.getElementById('navBtnApps').addEventListener('click', loadApps);
function loadApps(){
$('#mainCTN').load("/src/view/apps.php");
$('#tblApps').DataTable();
};
apps.php:
<div class="container pt-4">
<div class="col-12 border-bottom mb-5 pl-0">
<h3 class="display-4">
Your Apps
<button type="button" class="btn btn-success ml-2" data-toggle="modal" data-target="#new">
<i class="fas fa-plus mr-1"></i>
New
</button>
</h3>
</div>
<table id="tblApps" class="table table-striped">
<thead>
<tr>
<th>Application</th>
<th style="width:250px;">Action</th>
</tr>
</thead>
<tbody>
<?php foreach(scandir(dirname(__FILE__,3) . '/apps/') as $app){ ?>
<?php if(("$app" != "..") and ("$app" != ".") and ("$app" != ".htaccess")){ ?>
<tr>
<td><?=$app?></td>
<td>
<form method="post">
<a href="?p=apps&name=<?=$app?>" class="btn btn-sm btn-primary">
<i class="fas fa-eye mr-1"></i>
Details
</a>
<button type="submit" name="DeleteApp" value="<?=$app?>" class="btn btn-sm btn-danger">
<i class="fas fa-trash-alt mr-1"></i>
Delete
</button>
</form>
</td>
</tr>
<?php } ?>
<?php } ?>
</tbody>
</table>
</div>
When I press the navBtnApps button in my index very quickly, I can see that datatables is being activated. But as soon as the page stops loading, datatables gets deactivated. Any ideas why?
With your code:
$('#mainCTN').load("/src/view/apps.php");
$('#tblApps').DataTable();
$().load is asynchronous, so your #tblApps doesn't exist when you immediately (before it's finished loading) call .DataTable() on it.
Add the call into the $.load callback:
$('#mainCTN').load("/src/view/apps.php", function() {
$('#tblApps').DataTable();
});
jUqery.load() Load data from the server and place the returned HTML into the matched elements.
The data loaded will be available only after they are loaded, hence you need to run datatable in the callback.
Change :
function loadApps(){
$('#mainCTN').load("/src/view/apps.php");
$('#tblApps').DataTable();
};
To:
function loadApps(){
$('#mainCTN').load("http://localhost:63342/StackOverflow/1.html", ftion() {
$('#tblApps').DataTable();
});
};

Why Bootstrap Accordion is showing all the collapsible boxes?

I am using BOOTSTRAP ACCORDIAN to show invited speakers in our website.
I am in Wordpress 4.8.
The code used addtionally is the following:
function toggleChevron(e) {
var theAccordion = $('#accordion');
$(e.target)
.prev('.panel-heading')
.find('i.indicator')
.toggleClass('glyphicon-minus glyphicon-plus');
//$('#accordion .panel-heading').css('background-color', 'green');
theAccordion.find('.panel-heading').removeClass('highlight');
$(e.target).prev('.panel-heading').addClass('highlight');
}
$('#accordion').on('hidden.bs.collapse', toggleChevron);
$('#accordion').on('shown.bs.collapse', toggleChevron);
$('#accordion').on('show.bs.collapse', function () {
$('#accordion .in').collapse('hide');
});
I am getting the panel heading and body from a php:
PHP:
<div class="clearfix panel-group" id="accordion" >
<?php
global $wpdb;
$result = $wpdb->get_results( "SELECT * FROM `Invited_Speakers_auto`;");
foreach ( $result as $print ) { ?>
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title"> <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion" href="#<?php echo $print->Last_Name;?>"> <?php echo $print->First_Name;?> <?php echo $print->Last_Name;?>, <?php echo $print->Institute_Address;?>
</a> </h4>
</div>
<div id="<?php echo $print->Last_Name;?>" class="panel-collapse collapse in">
<div class="panel-body">
<img style="border-radius: 10%; padding: 10px; float: left;" src="<?php echo $print->Image_link;?>" alt="" width="20%" align="middle" />
<table style="width:79%;float: right;">
<tbody>
<td ><?php echo $print->Designation;?> </td>
</tr>
<tr>
<td style="display:block; width:50%;"><?php echo $print->Department_Address;?></td>
</tr>
<tr>
<td> Email Id: <?php echo $print->Email_Id;?> </td>
</tr>
</tbody>
</table>
<table>
<tbody>
<tr>
<td >Research Interests</td>
<td>:</td>
<td> <?php echo $print->Research_Interests;?></td>
</tr>
<tr>
<td>
Achievements
</td>
<td> : </td>
<td> <?php echo $print->Acheivements;?>
<button style="float:right;"><a style="color: white;" href="Home_page_Link" target="_blank" rel="noopener"> More Info </a> </button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<?php } ?>
</div>
When I am running the above code, all works fine except the following issue:
All collapsible body is opened when the page gets refreshed.
For successive double click on any panel-heading all settle down normally.
What is the problem?
I dont want any of the body should open when the page gets refreshed. Only when the user click one of the panel heading, the corresponding panel-body should be displayed and the rest should remain invisible.
PS: I have added all the javascript files at the footer.
Is that a problem??
Is it a running error?
Kindly clarify this. Click here to visit the page. In that Invited Speaker section has this problem.
Thank you in advance.
Try removing the in class from the panel-collapse element. Bootstrap adds this automatically when opening an expander panel - having this class set by default causes each panel to appear open.

Bootstrap delete row without refreshing page using modal

So far I can now delete the record using modal, but it just needs to go to the page delete-page. I want to delete the record with confirmation before deleting (using modal) and then delete the record without refreshing the page.
This is what I've tried so far:
<script type="text/javascript">
$(function() {
$(".btn-show-modal").click(function(e){
e.preventDefault();
$("#dialog-example").modal('show');
});
$("#btn-delete").click(function(e) {
$("#dialog-example").modal('hide');
});
});
</script>
<?php
$stmt2 = $conn->prepare("SELECT project_code, description FROM tblprojects");
$stmt2->execute();
for($i=0; $row2 = $stmt2->fetch(); $i++){
$project = $row2['project_code'];
$desc = $row2['description'];
?>
<tr class="record" id="record-">
<td>
<a href="project-detail.php?code=<?php echo $project; ?>">
<?php echo $project; ?></a>
</td>
<td><?php echo $desc; ?></td>
<td>
<a href="update-project.php?code=<?php echo $project; ?>" title="Update record">
<i class="icon-edit icon-white"></i>
</a>
</td>
<td>
<a href="#"
data-id="<?php echo $project; ?>"
id="<?php echo $project; ?>"
class="btn-show-modal" data-toggle="modal" title="Delete record">
<i class="icon-trash icon-white"></i>
</a>
</td>
<div class="modal hide fade" id="dialog-example">
<div class="modal-header">
<h5>Confirm Delete</h5>
</div>
<div class="modal-body">
<p class="modaltext">Are you sure you want to delete this record?</p>
</div>
<div class="modal-footer">
<a href="#" data-dismiss="modal" class="btn btn-info">No<a>
<a href="delete-project.php?code=<?php echo $project; ?>"
data-id="<?php echo $project; ?>"
class="btn btn-danger" id="btn-delete">Yes<a>
</div>
</div>
</tr>
<?php
}
?>
Any ideas? Thank you for your help.
Try this:
$("#btn-delete").click(function(e) {
e.preventDefault();
$.get(this.href, function(){
$("#dialog-example").modal('hide');
});
});
I do this all in the time in my projects but didn't want to post it since the code might not mean anything to others (and it's fairly long) but this is what I do:
<!-- Delete Modal -->
<div id="delete_modal" class="modal hide fade" role="dialog" aria-labelledby="myModalLabel" aria-hidden="false" tabindex="-1">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h3 id="myModalLabel">Delete</h3>
</div>
<div class="modal-body">
<div class="row-fluid">
<div class="span12"></div>
</div>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
<button id="delete_confirm" class="btn red btn-primary" data-dismiss="modal">Delete</button>
</div>
<!-- Submit Delete Modal -->
<div id="submit_delete_modal" class="modal hide fade" role="dialog" aria-labelledby="myModalLabel" aria-hidden="false" tabindex="-1">
<div class="modal-header">
<h3 id="myModalLabel">Deleting</h3>
</div>
<div class="modal-body">
<div class="row-fluid">
<div class="span12">
<div class="alert alert-info">Deleting... <img src="/images/loading.gif" alt="Deleting..." /></div>
</div>
</div>
</div>
</div>
So that's the two modals I use, one for the confirmation and another to show that the item is actually being deleted.
This is the JS:
$('.delete').click(function() {
$('#delete_modal .modal-body div div').html('Are you sure you want to delete this row?');
});
// this is the delete button in the confirmation modal
$('#delete_confirm').click(function() {
$('#delete_modal').modal('hide');
$('#submit_delete_modal').modal('show');
$.ajax({
url: '/delete-page',
data: { id: id },
type: "POST",
cache: false,
success: function(data) {
if (data === '1') {
// delete the row from the DOM
$('tr#record-' + id).fadeOut('slow').remove();
$('#submit_delete_modal .modal-body div div').html('<div class="alert alert-success"><i class="icon-ok-sign"></i> The row has been deleted</div>');
} else {
$('#submit_delete_modal .modal-body div div').html('<div class="alert alert-error"><i class="icon-exclamation-sign"></i> Deletion failed, please refresh the page and try again</div>');
}
},
error: function() {
$('#submit_delete_modal .modal-body div div').html('<div class="alert alert-error"><i class="icon-exclamation-sign"></i> Deletion failed, please refresh the page and try again</div>');
}
});
return false;
});
Just a pointer, looking at your tr markup, are you meaning to put the id from the database as part of the row id?
You have <tr class="record" id="record-"> so every row has the same id, if you add the correct parameter there every row will have a unique id and the delete part in the ajax callback will work.
The only thing that remains is to get the id when something is clicked but I'm finding it hard to tell what link you are using to perform the delete.
It should be something like this:
var id; // put this as the very first line of js, if it's in the global scope it can be accessed from anywhere, it's not best practise though.
$(document).on('click', '.some_class_name', function() {
id = $(this).parent().parent().attr('id').split('-').pop();
$('#delete_modal .modal-body').html('Are you sure that you want to remove this row?');
$('#delete_modal').modal('show');
// uncomment this to check you're getting the correct id and that it's not undefined etc
// alert('id');
return false;
});
I've tried to make everything generically named to avoid stuff from my projecting bleeding in but I might have missed some things and made some errors when renaming elements etc.

Categories