I have a search page on my web app which searches for events in my event table in my database. I would like to have it so that there is a delete button at the end of the search result with the ability to delete a database entry but also a pop up alert box before they delete the data.
My search results are displayed with the code below:
if(mysqli_num_rows($result) > 0) {
echo "<br>Result Found: ";
echo "<br><table>";
While($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>Event Number: " . $row['EventID'] . "</td>";
echo "</tr><tr>";
echo "<td>Location: " . $row['Location'] . "</td>";
echo "</tr><tr>";
echo "<td><input type='button' name='Delete' value='Delete' onClick='getConfirmation();'></td>";
}
echo "</table
I'm not too sure what to put in the javascript function. I want it to come up a basic alert box and if the user clicks the okay button then the action will be 'delete.php' and ideally another pop-up come up saying "Record Deleted Successfully". I also need to make sure to get the eventID from the record so that I can delete it successfully. So far for the JS function I have:
<script type = "text/javascript">
<!--
function getConfirmation() {
var retVal = confirm("Are you sure you would like to delete this record?");
if( retVal == true ) {
delete.php
document.write("Record deleted successfully");
}
else {
return false;
}
}
//-->
</script>
I know this is wrong but I am wondering how I can fix this?
Also could I just put it that if they press yes the php executes rather than going to delete.php?
To achieve this, you need to pass eventId in your onclick event as below:
if(mysqli_num_rows($result) > 0) {
echo "<br>Result Found: ";
echo "<br><table>";
While($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>Event Number: " . $row['EventID'] . "</td>";
echo "</tr><tr>";
echo "<td>Location: " . $row['Location'] . "</td>";
echo "</tr><tr>";
echo "<td><input type='button' name='Delete' value='Delete' onClick='getConfirmation(".$row['EventID'].");'></td>";
}
echo "</table>";
and in your JS code, you need to:
1. Get eventId in your js function.
2. Call ajax to delete that event.
3. show success alert after
<script type = "text/javascript">
function getConfirmation(eventId) {
var retVal = confirm("Are you sure you would like to delete this record?");
if( retVal == true ) {
$.ajax({
url: "delete.php",
method: "POST",
data: {eventId: eventId},
success: function (response) {
if(response.status) {
alert("Record Deleted Successfully");
}
}
});
} else {
return false;
}
}
</script>
Also, in your delete.php file, you need to get eventId by $_POST['eventId'] and you can execute delete query. and you need to send back to status. Hope it will help you.
Related
i need to know how on earth to get my checkbox value from PHP that is in a loop and also might be in DOM. I have to put that checkbox inside the loop to make it being shown on each row of databases. I tried to call it back using different method but none success. The last part is javascript but i don't have any clue how to do that.
My code for javascript index.php.
function ajaxSearchUpdater(p){
$("#result").show();
var x = $("#search").val();
var y = $("#edulevel").val();
var pagelim = $("#pagefpe").val();
var pagenumber = p;
var checkb = $(".sBorrow").val()
$.ajax({
type:'POST',
url:'userres.php',
data:'q='+x+'&e='+y+'&pagelim='+pagelim+'&pageno='+pagenumber+'&checkb='+checkb,
cache:false,
success:function(data){
$("#result").html(data)
}
});
}
$(document).ready(function(e) {
ajaxSearchUpdater(1); // fires on document.ready
$("#search").keyup(function() {
ajaxSearchUpdater(1); // your function call
});
$("#edulevel").click(function() {
ajaxSearchUpdater(1); // your function call
});
$("#pagefpe").click(function() {
ajaxSearchUpdater(1); // your function call
});
$('.sBorrow').on('change', function(){
var checkBorrow = $(event.target);
var isChecked = $(checkBorrow).is(':checked');
alert("test");
alert(isChecked);
alert('checkbox'+checkborrow.attr('id')+'is checked:'+isChecked);
});
});
$(document).ready(function() {
$('.sBorrow').on('change', function(event) {
var checkbox = $(event.target);
var isChecked = $(checkbox).is(':checked');
alert('checkbox ' + checkbox.attr('id') + ' is checked: ' + isChecked);
});
});
My code for the checkbox in PHP userres.php
if($stmt->rowCount() > 0){
$r=$stmt->fetchAll();
echo "<table class='tablesorter-blackice' id='myTable' style='width:97%; table-border: 1'>";
echo "<thead>";
echo "<tr>";
echo "<th>No.</th>";
echo "<th>No.Matric</th>";
echo "<th>Name</th>";
echo "<th>Programme</th>";
echo "<th>Title</th>";
echo "<th>Thesis Level</th>";
echo "<th>Serial Number</th>";
echo "<th>Availability</th>";
echo "<th>Select book (Max 3)</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";
foreach($r as $row){
$sBorrow = $_SESSION['sBorrow'];
echo "<tr align='center'><td>". ($startrow+1) ."</td><td>". $row['matricno'] ."</td><td>". $row['studentname'] ."</td><td>". $row['programme'] ."</td><td>". $row['title'] ."</td><td>". $row['thesis_level'] ."</td><td>". $row['serialno'] ."</td><td>". $row['bavailable'] ."</td><td>
<form method='post'>
<input type='checkbox' name='sBorrow' id='sBorrow' class='sBorrow' value='". $row['serialno'] ."'>
</form></td></tr>";
$startrow++;
//echo $row['education_level'];
}
echo "</tbody>";
echo "</table>";
I don't know what to do since i'm calling that page from ajax and uhh how should i explain this.
You know index.php -> userres.php -> index.php using ajax.
for javascript on the bottom part is what i have done and i dont think its right. I tried to create one other document ready for this checkbox but still even alert not showing up. I'm confused. please help T_T
Sorry, but I have to ask one more question. Google couldn´t help me :(
I try to create a user control management in a CMS.
The problem is that I am completely knew to javascript and jQuery and I have to delete a table row on button click without refreshing the page. The idea is to set the row display:hidden, but I don´t know how to get the id of a row.
Here is my code:
<?php
$abfrage= mysql_query("SELECT * FROM user ORDER BY id asc");
//$ergebnis = mysql_query($abfrage) or die( mysql_error() );
echo "<table>";
echo"<caption>Mitglieder<br></caption>";
echo"<table border=\"1\" style=\"width:300px\">";
echo "<th>ID</th>
<th>Name</th>
<th>Vorname</th>
<th>Rolle</th>
<th>Funktionen</th>";
//loop, um alle Nutzer zu identifizieren
while($row = mysql_fetch_object($abfrage))
{
echo "<tr>";
echo "<td align=center id =",$row->id,">",$row->id,"</td>";
echo "<td align=center>" ,$row->Name,"</td>";
echo "<td align=center>",$row->Vorname,"</td>";
//Vorbelegung
echo "<td align=center><select><option selected = \"selected\">",$row->Rolle,"</option>";
//loop, um alle Rollen zu identifizieren. AKTUELL: doppelte Rollen werden noch doppelt angezeigt. Eventuell Rollen auslaagern
$file = mysql_query("SELECT Rolle FROM user WHERE 1");
while ($role = mysql_fetch_row($file))
{
if ($role[0]!= $row->Rolle) {
echo "<option value=".$role[0].">",$role[0],"</option>";
}
}
echo "</select></td>";
echo "<td align=center><button type = \"button\" onCLick = \"deleteUser()\">Löschen</button></td>";
}
echo "</table>";
?>
<html>
<script type="text/javascript">
function deleteUser() {
alert("And it works");
document.getElementById(id).style.display = 'none'
}
</script>
</html>
The problem is here:
echo "<td align=center id =",$row->id,">",$row->id,"</td>";
Is this the right way to create an id to every row?
And if somebody knows how to realize it, I want to have an "deleting" (Deleting is obviously the wrong word because it is only hidden) animation.
Thank you in advance!
Ps: I know, that I have to change mysl to SQLi :)
I'm not really a FAN of JQuery because makes you forgeth the very basics of Javascript! it really simplyfies some things but... hmm dunno!
maybe this "function" could help you:
function dropRow(rowId) {
try {
var tblResponse= document.getElementById('tblResponse');
var rowCount = tblResponse.rows.length;
for(ix=0; ix < rowCount;ix++) {
var row = tblResponse.rows[ix];
var id = row.cells[0].childNodes[0].id; //The ID of something what identifies the Row
if(id == 'dropRow'+rowId) {
tblResponse.deleteRow(ix);
rowCount--;
ix--;
}
}
}catch(e) {
alert(e);
}
}
You can use the remove function within jQuery.
You will want to give the ID to the <tr> and not a <td> within the row, next your deleteUser function should take the "id" as an argument, and finally you should delete the row from within the deleteUser function. But you will need a way to inform your database that the user has been deleted, perhaps ajax to an API might work but I don't know how you have your system set up.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function deleteUser(id){
$(id).remove();
// Do something to let the server know the user was deleted
}
</script>
</head>
<body>
<?php
$abfrage= mysql_query("SELECT * FROM user ORDER BY id asc");
echo "<table>";
echo "<caption>Mitglieder<br></caption>";
echo "<table border=\"1\" style=\"width:300px\">";
echo "<thead><tr><td>ID</td><td>Name</td><td>Vorname</td><td>Rolle</td><td>Funktionen</td></td><thead>";
while($row = mysql_fetch_object($abfrage)){
echo "<tr id='".$row->id."'>";
echo "<td align='center'>".$row->id."</td>";
echo "<td align='center'>".$row->Name."</td>";
echo "<td align='center'>".$row->Vorname."</td>";
echo "<td align='center'><select><option selected=\"selected\">".$row->Rolle."</option>";
$file = mysql_query("SELECT Rolle FROM user WHERE 1");
while ($role = mysql_fetch_row($file)){
if ($role[0]!= $row->Rolle)
echo "<option value=".$role[0].">".$role[0]."</option>";
}
echo "</select></td>";
echo "<td align='center'><button type = \"button\" onclick = \"deleteUser(".$row->id.")\">Löschen</button></td>";
echo "</tr>"
}
echo "</table>";
?>
</body>
</html>
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I've looked through the existing questions and i don't believe they are answering my question.
I have created a table that gets populated using PHP and MySQL. I have got my add function working so the user can ADD a new row, however I would like the user to remove specific rows. Each row has a remove icon that I would like when clicked to remove ONLY that row.
Home.php (where table is created)
<table class="table table-bordered table-striped table-responsive">
<tr class="header">
<td>id</td>
<td>Rep</td>
<td>Date</td>
<td>Name</td>
<td>P_O</td>
<td>Due Date</td>
<td>Terms</td>
<td>Aging</td>
<td>Open Balance</td>
<td>remove</td>
</tr>
<?php
while($row = mysql_fetch_array($query))
{
$className ="";
if ($row['Aging'] >= 45) {
$className="danger";
}
else if($row['Aging'] >= 25 && $row['Aging'] <= 44) {
$className="warning";
}
echo "<tr class='$className'>";
echo "<td>".$row['id']."</td>";
echo "<td>".$row['Rep']."</td>";
echo "<td>".$row['Date']."</td>";
echo "<td>".$row['Name']."</td>";
echo "<td>".$row['P_O']."</td>";
echo "<td>".$row['Due_Date']."</td>";
echo "<td>".$row['Terms']."</td>";
echo "<td>".$row['Aging']."</td>";
echo "<td>".$row['Open_Balance']."</td>";
echo "<td><button type='button' class='btn btn-link'><i class='iconhover fa fa-check-circle fa-2x'></i></button></td>";
}
?>
</table>
This is the remove button:
<button type='button' class='btn btn-link'><i class='iconhover fa fa-check-circle fa-2x'></i></button>
I would like it to remove the row that its currently part of when clicked. Any help?
Here is my new code, however it still doesn't seem to be deleting the row
home.php:
while($row = mysql_fetch_array($query))
{
$className ="";
if ($row['Aging'] >= 45) {
$className="danger";
}
else if($row['Aging'] >= 25 && $row['Aging'] <= 44) {
$className="warning";
}
echo "<tr class='$className'>";
echo "<td>".$row['id']."</td>";
echo "<td>".$row['Rep']."</td>";
echo "<td>".$row['Date']."</td>";
echo "<td>".$row['Name']."</td>";
echo "<td>".$row['P_O']."</td>";
echo "<td>".$row['Due_Date']."</td>";
echo "<td>".$row['Terms']."</td>";
echo "<td>".$row['Aging']."</td>";
echo "<td>".$row['Open_Balance']."</td>";
echo "<td><button action='deletepage.php' method='POST' value='" .$row['id']. "' class='btn btn-danger'> Delete</button></td>";
}
deletepage.php:
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if(isset($_GET['id'])){
$userID = (int) $_GET['id'];
if(!empty($_GET['id'])) {
$delete = mysql_query("DELETE FROM Book1 WHERE id='$userID'");
}
if($delete) {
echo "Record deleted successfully";
}
else {
echo "Sorry, record could not be deleted";
}
}
You can do by directing it to the delete page like this:
Delete
Or with javascript AJAX call:
Delete
and use $.post to the deletion page
UPDATE:
the deletion page deletepage.php may contain the following:
<?php
require('dbconn.php');
if(isset($_POST['id'])){
$userID = (int) $_POST['id'];
if(!empty($_POST['id'])){
$delete = mysql_query("DELETE FROM users WHERE id='$userID'");
}
if($delete){
echo "Record deleted successfully";
}else{
echo "Sorry, record could not be deleted";
}
}
?>
users.php
<?php
require('dbconn.php');
$get = mysql_query("SELECT * FROM users");
while($row = mysql_fetch_array($get)) {
echo '<p>';
echo $row['id'] . ' - ' . $row['user'];
?>
Delete
</p>
<?php } ?>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
function confirmDeletion(id){
$.post('deletepage.php', { id:id }, function(data){
alert(data);
location.reload();
});
}
</script>
P.S:
It's very recommended to quit using mysql_query() in this way and instead use PDO to avoid SQL injection
I would change the button to include the value of the row id, by adding a value attribute to the button html:
value='" .$row['id']. "'
You can then capture the click event using jquery / javascript, and use an ajax call to remove the record from your database. It would look something like:
$('.btn-lnk').on('click',function() {
var id = $(this).val();
$.ajax({
type: "POST",
url: "yourPageThatDeletesRow.php",
data: { id: id },
success: function(response) {
if(response === 'success') {
//delete row showing on the page
$(this).closest('tr').remove();
} else {
//handle error
}
} //consider handling ajax error case
});
});
The ajax call will execute the code on yourPageThatDeletesRow.php. You can get the row id using $_POST['id'] and delete the data using that id. If the delete is successful, echo the string 'success'. Consider returning the error from the database if it's not successful, and handling that case in the return of the ajax
Here is a simplified JS Fiddle showing how the passing of the id and row deletion work.
You will need a delete button if your going to do it the way ive done it.
if (isset($_POST['delete'])){
$userid = $_POST['userid'];
$sql = "DELETE FROM users WHERE userid = '$userid';";
if ($conn->query($sql) === true){
//echo 'Click here to view modified patients';
}
}
Use this code:
<?php $temp_pre_ID = $row['id'];?>
<INPUT TYPE="button" onClick="window.location='home.php?Action=del&CusID=<?php echo $temp_pre_ID;?>'" value="Delete">
My delete function isn't working.
This is my table with the delete button.
// retrieve table contents
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
//creating new table row per record
echo "<tr>";
echo "<td class='text-align-center'><input type='checkbox' name='item[]' class='checkboxes' value='{$employeeid}' /></td>";
echo "<td>{$name}</td>";
echo "<td>{$title}</td>";
echo "<td>{$phone}</td>";
echo "<td>{$supplier_name}</td>";
echo "<td>{$created}</td>";
echo "<td>";
// update record
echo "<a href='update_product.php?employeeid={$employeeid}' class='btn btn-info margin-right-1em'>";
echo "<span class='glyphicon glyphicon-edit'></span> Rediger";
echo "</a>";
// delete record
echo "<a delete-employeeid='{$employeeid}' delete-file='delete_product.php' class='btn btn-danger delete-object'>";
echo "<span class='glyphicon glyphicon-remove'></span> Slet";
echo "</a>";
echo "</td>";
echo "</tr>";
}
//end table<br>
echo "</table>";
This is my delete function
// delete single record
$(document).on('click', '.delete-object', function(){
// php file used for deletion
var delete_file = $(this).attr('delete-file');
var id = $(this).attr('delete-id');
var q = confirm("Are you sure?");
if (q == true){
$.post(delete_file, {
object_id: id
}, function(data){
location.reload();
}).fail(function() {
alert('Unable to delete.');
});
}
return false;
});
I got the code from a tutorial that I modified a lot. Everything else is working, except the delete function.
PHP CODE
<?php
// check if value was posted
if($_POST){
// include database and object file
include_once 'config/database.php';
// delete query
$query = "DELETE FROM employeestest WHERE employeeid = ?";
$stmt = $con->prepare($query);
$stmt->bindParam(1, $_POST['object_employeeid']);
if($stmt->execute()){
// redirect to read records page and
// tell the user record was deleted
echo "Medarbejderen er slettet.";
}else{
echo "Medarbejderen kunne ikke slettes.";
}
}
?>
Change
var id = $(this).attr('delete-Id');
to
var id = $(this).attr('delete-employeeid');
And, Change $.post to $.ajax as i've given
<script>
$(document).on('click', '.delete-object', function(){
var delete_file = $(this).attr('delete-file');
var id = $(this).attr('delete-employeeid');
var q = confirm("Are you sure?");
if (q == true)
{
$.ajax({url:delete-file,cache:false,success:function(result){
alert('Successfully Deleted');
}});
}
return false;
});
</script>
Maybe you just made grammar mistake
'delete-id' => 'delete-employeeid'
I dont know how to use ajax in my problem:
I have a function in php (assign) that update a temporary table in database, I want to when user user click on a button (feedback function that is defined in javascript) this function (assign) run, what should I do?
<script>
function feedback(){
var boxes = document.getElementsByClassName('box');
for(var j = 0; j < boxes.length; j++){
if(boxes[j].checked) {
assign(1);
}
else{
assign(0);
}
}
}
</script>
<?php
$con = mysql_connect("localhost", "root", "")
or die(mysql_error());
if (!$con) {
die('Could not connect to MySQL: ' . mysql_error());
}
mysql_select_db("project", $con)
or die(mysql_error());
$result = mysql_query("select * from words");
echo "<table border='1'>
<tr>
<th>word</th>
<th>meaning</th>
<th>checking</th>
</tr>";
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['word'] . "</td>";
$idd= $row['id'] ;
echo "<td>". "<div class='hiding' style='display:none'>".$row['meaning']."</div>"."</td>";
echo "<td>";
echo "<input class=\"box\" name=\"$idd\" type=\"checkbox\" value=\"\"> ";
echo "</td>";
echo "</tr>";
}
echo "</table>";
function assign($checkparm){
//mysql_query("update words set checking=$checkparm ");
mysql_query("create TEMPORARY TABLE words1user1 as (SELECT * FROM words) ");
mysql_query("update words1user1 set checking=$checkparm ");
}
mysql_close($con);
?>
<button onclick="ShowMeanings()">ShowMeanings</button>
<button onclick="feedback()">sendfeedback</button>
There is only one way to call a php function after the page is loaded:
1.ajax:
function callPHP() {
$.ajax ({
url: "yourPageName.php",
data: { action : assign }, //optional
success: function( result ) {
//do something after you receive the result
}
}
in your PHP, write
if ($_POST["action"] == "assign")
{
assign(your parameters); //You need to put the parameters you want to pass in
//the data field of the ajax call, and use $_POST[]
//to get them
}
There are many great guides on the internet. I will however suggest you get too know JQuery. It will help you on your learning curve.
function ajaxCall(){
$.ajax({
type: "GET",
url: "scripts/on/serverside.php"
});
};