PHP Ajax MySQL Table Row Delete - javascript

I wrote the code to delete MySQL table rows. But when I click on delete icon, nothing happens. Could someone please tell me what's left in my code?
<?php
include_once 'include/DatabaseConnector.php';
$query1="SELECT * FROM MyTable;";
$result1=DatabaseConnector::ExecuteQueryArray($query1);
?>
<script type="text/javascript">
function deleteRow(tableName,colName,id){
$.ajax({
type: "POST",
url: "delete.php",
data: "tableName=tableName&colName=colName&id=id",
success: function(msg){
alert( "Row has been updated: " + msg );
}
});
}
</script>
<table id="newspaper-b" border="0" cellspacing="2" cellpadding="2" width = "100%">
<thead>
<tr>
<th scope="col">Opr</th>
<th scope="col">Flt Num</th>
<th scope="col">From</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<?php foreach ($result1 as $row):?>
<tr>
<td><?php echo $row['airlineName'];?></td>
<td><?php echo $row['flightNum'];?></td> <td><?php echo $row['from'];?></td>
<td>
<div title='Delete' onclick='deleteRow(<?php echo 'flightschedule','flightNum',$row['flightNum']; ?>)'>
<img src='images/delete.png' alt='Delete' />
</div>
</td>
</tr>
<?php endforeach;?>
</tbody>
delete.php
<?php
/* Database connection */
include_once 'include/DatabaseConnector.php';
if(isset($_POST['tableName']) && isset($_POST['colName']) && isset($_POST['id'])){
$tableName = $_POST['tableName'];
$colName = $_POST['colName'];
$id = $_POST['id'];
$sql = 'DELETE FROM '.$tableName.' WHERE '.$colName.' ="'.$id.'"';
mysql_query($sql);
} else {
echo '0';
}
?>

have you checked your PHP log to see if there is an error?
what is Ajax.Request ? if you are using the prototype library, where is it included in your HTML code?
finally, are you sure your PHP code is called? (check using for instance the Web Developper Tools in Chrome browser, "Requests" tab)

You have an error on this line
<div title='Delete' onclick='deleteRow(<?php echo 'flightschedule','flightNum',$row['flightNum']; ?>)'>
this will print
<div title='Delete' onclick='deleteRow(flightscheduleflightNumid)'>
You have to change it to
<div title='Delete' onclick='deleteRow("flightschedule","flightNum",<?php $row['flightNum']; ?>)'>
to work.
Best wishes
Update: For the above code to work also add
<script src="js/jquery.js" type="text/javascript" ></script>
or load it from the internet
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.js"></script>
to include Jquery at the header of html. I have tested its ok now.

you send not your data to the delete.php file, because in the attribute dated you seize them badly. Here is this code I have just tested him(it) and that seems to work.
data: "tableName="+tableName+"&colName="+colName+"&id="+id+"",
function deleteRow(tableName,colName,id){
$.ajax({
type: "POST",
url: "delete.php",
data: "tableName="+tableName+"&colName="+colName+"&id="+id+"",
success: function(msg){
alert( "Row has been updated: " + msg );
}
});
}

Related

How to fetch results from MySQL database using AJAX on button click

I am new to PHP and ajax so please be easy on me. I am trying to fetch MySQL results using AJAX. I have manged to get to this point from the research I found across the internet. I am doing this inside WordPress if this might help. I am getting this error -
Uncaught Error: Call to a member function get_results() on null in script.php:13 Stack trace: #0 {main} thrown in script.php on line 13
test.php
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<button type="button">Click</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<p></p>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("button").click(function(){
$.ajax({
type: 'POST',
url: 'script.php',
success: function(data) {
jQuery("p").html(data);
}
});
});
});
</script>
</body>
</html>
script.php
<?php
echo' <table border="1">
<th colspan="5" style="text-align:center;"> <h2 class="tomorrow">GRADES</h2> </th>
<tr>
<th>Day</th>
<th>Comp</th>
<th>Exam Type</th>
<th>Grade</th>
<th>Previous Score</th>
</tr>'?>
<?php
global $wpdb;
$result = $wpdb->get_results ( "SELECT * FROM wp_mytab
WHERE date=DATE(NOW())
UNION ALL
SELECT * FROM wp_mytabb
WHERE date=DATE(NOW())
ORDER BY date, comp ASC;" );
foreach ( $result as $print ) {
?>
<tr>
<td><?php echo $print->day;?></td>
<td><?php echo $print->comp;?></td>
<td><?php echo $print->examtype;?></td>
<td><?php echo $print->grade;?></td>
<td><?php echo $print->previouscore;?></td>
</tr>
<?php }
?>
</table>
?>
What could be wrong here?
You can't use $wpdb outside of wordpress code structure in a stand alone PHP file.
To do that you should include some wordpress libraries
Add this at beginning of your php code.
$path = $_SERVER['DOCUMENT_ROOT'];
include_once $path . '/wp-includes/wp-db.php';
Make sure your $path be right

How update records in the database and remove a table row on button click using ajax?

So I have created an HTML table with dynamic rows. On the end the every row there is a button. When that button on the particular row is clicked, the row needs to removed without page refresh.
So I'm trying to do it by changing the values of column in database on button click. There is a field named 'status' in my database, which is initially set to 'unchecked'. But when I click the button, the update query is to be triggered hence changing the 'status' field to 'checked' on that particular row, and removing that particular.
newCust.php
<table class="table table-bordered table-striped table-light table-
responsive text-nowrap">
<thead class="thead-dark">
<tr>
<th class="col"><label> nID</label></th>
<th class="col"><label> CUSTOMER NAME </label></th>
<th class="col"><label> ADDRESS </label></th>
<th class="col"><label> CITY </label></th>
<th class="col"><label> STATUS </label></th>
</tr>
</thead>
<tbody>
<?php
<!-- GETTING DATA FROM THE TABLE WHERE STATUS FIELD IS UNCHECKED -->
$query = "select * from mx_newcustomer where status = 'unchecked'";
$result = mysqli_query($db,$query);
while($res = mysqli_fetch_array($result)){
$nID = $res['nID'];
?>
<tr>
<td><?php echo $nID; ?></td>
<td><?php echo $res['customername']; ?></td>
<td><?php echo $res['address']; ?></td>
<td><?php echo $res['city']; ?></td>
<td><button type="button" id="button<?php echo $nID; ?>" class="btn btn-
dark" >Ok</button></td>
</tr>
<script>
<!-- AJAX TO UPDATE RECORDS IN THE DATABASE-->
$(document).ready(function () {
$("#button<?php echo $nID ?>").click(function(){
alert('Test');
jQuery.ajax({
type: "POST",
url: "updateCust.php",
<--TRYING TO
PASS THE CLICKED BUTTON ID. I BELIEVE THIS IS WHAT I'M DOING WRONG-->
data: {"nID":$('#button<?php echo $nID ?>').serialize()},
success: function(response)
{
alert("Record successfully updated");
}
});
});
});
</script>
updateCust.php
$db = mysqli_connect("credentials");
$nID = $_POST['nID'];
$query = "UPDATE mx_newcustomer SET status = 'checked' WHERE nID =
'$nID'";
$res = mysqli_query($db, $query);
error_reporting(E_ALL);
ini_set('display_errors','On');
I'm not getting any errors, but the update query is not being triggered either. The expected result is remove the table row whose button has been clicked, without the page being refreshed.
Don't use .serialize(), it returns a string in the form name=value. But your button doesn't have a name or value, so there's nothing to serialize.
Change it to:
data: {"nID": <?php echo $nID ?>},
To delete the row, you can use:
success: function() {
$("#button<?php echo $nID?>").closest("tr").remove();
}

Popup content dependent on AJAX result

I am not that experienced in web developing, so sorry for rookie mistakes;)
In HTML, I want to create a dynamic popup window(div hidden by CSS). On the click of a button I am performing an AJAX post request. The result of the request is a string, which is stored in a hidden input field on the HTML page.
The popup contains a table with the content submitted by the string.
However now I want to retrieve the string via a PHP $_GET or $_POST request.
This is not working at the moment and I don't understand why.
Opening the popup window I am getting these errors:
Notice: Undefined index: popupcontenthidden in ...
Warning: Invalid argument supplied for foreach() in
The HTML:
<div class="popupcontent">
<span class="helper"></span>
<div>
<div class="popupclose">X</div>
<h3>UPDATE DATABASE ENTRY</h3>
<h4>Enter values:</h4>
<table id="popupresult">
<form name='form' action="" method='post'>
<input type='text' name='popupcontenthidden' id='popupcontenthidden'>
</form>
<tr>
<th>Field</th>
<th>Type</th>
<th>Null</th>
<th>Key</th>
<th>Default</th>
<th>Extra</th>
<th>Value</th>
</tr>
<?php
$rows = json_decode($_POST['popupcontenthidden']);
foreach ( $rows as $print ) {
?>
<tr>
<td><?php echo $print->Field; ?></td>
<td><?php echo $print->Type; ?></td>
<td><?php echo $print->Null; ?></td>
<td><?php echo $print->Key; ?></td>
<td><?php echo $print->Default; ?></td>
<td><?php echo $print->Extra; ?></td>
</tr>
<?php } ?>
</table>
</div>
The JS:
$.ajax({
type:'POST',
url: '../wp-content/plugins/ars-management/admin/ars-management-admin-ajax.php',
data: {function: "update", entries: entries},
success: function(response) {
var rows = response;
//hand data to html hidden input
document.getElementById("popupcontenthidden").value = rows;
//open popup on click
$(".popupcontent").show();
}
});
I understand that the second error is happening because $rows is empty.
But how can I fix the issue and retrieve the string from the input field? I can confirm that the string is correctly stored in the input field so all the AJAX stuff works.
Thank you so much!
A kind of solution here:
HTML:
<div class="popupcontent">
<span class="helper"></span>
<div class="popupclose">X</div>
<h3>UPDATE DATABASE ENTRY</h3>
<h4>Enter values:</h4>
<table id="popupresult">
<thead>
<tr>
<th>Field</th>
<th>Type</th>
<th>Null</th>
<th>Key</th>
<th>Default</th>
<th>Extra</th>
<th>Value</th>
</tr>
</thead>
<tbody id="myPopupContentTableBody"></tbody>
</table>
</div>
Javascript:
$.ajax({
type:'POST',
url: '../wp-content/plugins/ars-management/admin/ars-management-admin-ajax.php',
data: {function: "update", entries: entries},
success: function(response) {
$('#myPopupContentTableBody').html(response);
//open popup on click
$(".popupcontent").show();
}
});
PHP:
<?php
...
$rows = myPHPCalculation;
foreach ($rows as $print){
echo '
<tr>
<td>'.$print['Field'].'</td>
<td>'.$print['Type'].'</td>
<td>'.$print['Null'].'</td>
<td>'.$print['Key'].'</td>
<td>'.$print['Default'].'</td>
<td>'.$print['Extra'].'</td>
</tr>
';
}
...

AJAX event works but not reflect PHP MYSQL result simultaneously without refresh.

Hello guys I am new to AJAX and I'm developing DB list like CRUD and one of delete feature I used with AJAX actually it deletes record but only reflect after manual refresh not simultaneously so I need your help with AJAX.
List.php
<?php
include "db.php";
$sql = "SELECT * FROM users";
$query = $conn->query($sql);
?>
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
$(document).on('click','#btn_delete',function(){
var uid = $(this).data("id1");
if(confirm('Are You Sure To Delete '+uid+' ?'))
{
$.ajax({
url: 'delete.php',
type: 'POST',
data: 'uid='+uid,
dataType: 'text',
success:function(data){
//alert(data);
}
});
}
});
});
</script>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Contact</th>
<th>Skills</th>
<th>Edit</th>
</tr>
<?php
while($row = $query->fetch_object()){
//echo $row->name."<br>";
?>
<tr>
<td><?php echo $row->uid; ?></td>
<td><?php echo $row->name; ?></td>
<td><?php echo $row->contact; ?></td>
<td><?php echo $row->skills; ?></td>
<td id="edit">
<button calss="delete_btn" type="submit" id="btn_delete" name="delete" value="DELETE" data-id1="<?php echo $row->uid; ?>">DELETE</button>
<!-- <a href="delete.php" data-id2="<?php echo $row->uid; ?>" id="delete" alt="DELETE" >Delete</a> -->
Update
</td>
</tr>
<?php } ?>
</table>
Whenever I press Delete button it actually delete record on first hand from database that mean ajax works but simultaneously table is not refresh, deleted entry remain in table till next refresh.
Delete.php
<?php
include "db.php";
$uid = $_POST['uid'];
$sql = "DELETE FROM users WHERE uid='".$uid."'";
$conn->query($sql);
$conn->close();
?>
<p id="check">Deleted</p>
I see some issues with this code and currently only partial or round about answers so I thought I would lend a hand :)
The dynamic rows you create inside your while loop have buttons that have a static ID across all delete buttons.
This could cause problems because ID's are supposed to be unique.
You misspelled class.
I removed the ID, corrected the spelling on class, and updated the JavaScript to use the button class instead of ID.
Since the button is in the table we can use it as a marker for which row to remove from the table.
This can be accomplished by calling closest: var tr = $(this).closest("tr");
Once the AJAX succeeds we can now remove that row: tr.remove();
The jQuery AJAX function has gone through some changes recently as the success callback was deprecated and then removed in 3.0 see Deprecation Notice.
This would cause your success call to not fire as it doesn't exist in 3.0 and from your question we can see that your using version 3.2.1.
I have replaced the callback with the updated call.
Here is the solution I came up with:
<script>
$(document).ready(function() {
$(document).on("click", ".btn_delete", function(){
var tr = $(this).closest("tr");
var uid = $(this).data("id1");
if (confirm("Are You Sure To Delete " + uid + "?")) {
$.ajax({
url: "delete.php",
type: "POST",
data: "uid=" + uid,
dataType: "text",
done: function(data){
tr.remove();
}
});
}
});
});
</script>
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Contact</th>
<th>Skills</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
<?php
while($row = $query->fetch_object()){
//echo $row->name."<br>";
?>
<tr>
<td><?php echo $row->uid; ?></td>
<td><?php echo $row->name; ?></td>
<td><?php echo $row->contact; ?></td>
<td><?php echo $row->skills; ?></td>
<td id="edit">
<button class="delete_btn" type="submit" name="delete"
value="DELETE" data-id1="<?php echo $row->uid; ?>">DELETE</button>
<a href="form.php?link=<?php echo $row->uid; ?>"
value="<?php echo $row->uid; ?>" alt="UPDATE">Update</a>
</td>
</tr>
</tbody>
<?php } ?>
</table>
On another note the PHP call to your MySql in Delete.php is susceptible to injection attacks here is some documentation on that in PHP < 5.5 see Example 5.50 An example SQL Injection Attack and in PHP >= 5.5 as the function was deprecated in 5.5.
You can delete the element in the success callback function like so:
$.ajax({
url: 'delete.php',
type: 'POST',
data: 'uid='+uid,
dataType: 'text',
success:function(data){
//if using jquery
//$('tr').filter(':has(td:first:contains(' + uid + '))').remove();
$('tr').filter(function() {
return $(this).find('td:first').text() == uid;
}).remove();
//if not
var table = document.getElementsByTagName('table')[0];
var rows = table.getElementsByTagName('tr');
for (var i = 0; i < rows.length; i++) {
if (rows[i].children[0].textContent == uid) {
table.removeChild(rows[i]);
}
}
}
});
You can use this:
$.ajax({
url: 'delete.php',
type: 'POST',
data: 'uid='+uid,
dataType: 'text',
success:function(data){
window.location.href = 'YOUR PAGE';
}
})
You can make the page to reload automatically after successful ajax call. Try This:
$.ajax({
url: 'delete.php',
type: 'POST',
data: 'uid='+uid,
dataType: 'text',
success:function(data){
location.reload();
}
})

Delete row in table html using ajax and php

How Delete row in table html using ajax and php,
I need delete row in html table select row and click button delete make delete using ajax Currentally can make delete without ajax but I need delete row and stay on page without make submit on other page
code javaScript
function getDelete()
{
$.ajax({
type:"post",
//dataType:"json",
data:"id="+id,
url:"delete_address.php?id=$id", // url of php page where you are writing the query
success:function(json)
{
},
error:function(){
}
});
}
code html and php
<?php
$resualt=mssql_query("SELECT * FROM Address where user_id='$UserId' ") ;
echo "<table border='1' class='imagetable' id='imagetable'
width='400px' >\n";
echo '<thead>'.'<tr>';
echo '<th>Street</th>'.'<th>Quarter</th>'.
'<th>From</th>'.'<th>To</th>'.'<th>Notes</th>';
echo '</tr>'.'</thead>';
echo '<tbody>';
while ($row = mssql_fetch_assoc($resualt)) {
$fromDate=$row['from_date'];
$toDate=$row['to_date'];
echo " <tr onClick='myPopup($row[id])'".
( $_GET['id'] == $row['id'] ?
"style='background-color: green;'":"").">\n"."<td >
{$row['street']} </td>\n".
"<td>{$row['quarter']}</td>\n"."<td>$fdate2</td>\n".
"<td>$tdate2</td>\n"."<td>{$row['other_info']}</td>\n";
}
echo '</tbody>';
echo "</table>\n";
?>
<?php
echo"<a class='button-link' onClick='getDelete()'>delete</a>";
?>
code sql query
<?php
$idEmploye=$_GET['id'];
$userId=$_GET['user_id'];
$db_host = 'MOHAMMAD-PC\SQL2005';
$db_username = 'sa';
$db_password = '123321';
$db_name = 'db_test';
mssql_connect($db_host, $db_username, $db_password);
mssql_select_db($db_name);
mssql_query("DELETE FROM Address
WHERE id='$idEmploye' ; ") or die(mssql_error()) ;
echo '<script language="javascript">';
echo 'alert("successfully deleted ")';
echo '</script>';
echo "<script>setTimeout(\"location.href ='address.php';\",10); </script>";
?>
Any Help Very Thanks
Try this solution
HTML:
<table>
<tr>
<td>Username</td>
<td>Email</td>
<td>Action</td>
</tr>
<tr>
<td>TheHalfheart</td>
<td>TheHalfheart#gmail.com</td>
<td>
<input type="button" class="delete-btn" data-id="1" value="Delete"/>
</td>
</tr>
<tr>
<td>freetuts.net</td>
<td>freetuts.net#gmail.com</td>
<td>
<input type="button" class="delete-btn" data-id="2" value="Delete"/>
</td>
</tr>
</table>
We have two button's properties call data-id and class delete-btn
AJAX jQuery:
<script language="javascript">
$(document).ready(function(){
$('.delete-btn').click(function(){
// Confirm
if ( ! confirm('Are you sure want to delete this row?')){
return false;
}
// id need to delete
var id = $(this).attr('data-id');
// Current button
var obj = this;
// Delete by ajax request
$.ajax({
type : "post",
dataType : "text",
data : {
id : id
},
success : function(result){
result = $.trim(result);
if (result == 'OK'){
// Remove HTML row
$(obj).parent().parent().remove();
}
else{
alert('request fails');
}
}
});
});
});
</script>
In PHP:
Get the ID and delete
Reponse OK if success
Sorry i'm learning English, please fix if its bad

Categories