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
Related
I am trying to make an AJAX call to my PHP Script. I can echo the results from my data. php just fine. My question is how do I make the call from index.html to pull the table results in data.php.
<?php
$pullData = file_get_contents('https://api.rentcafe.com/rentcafeapi.aspx?requestType=apartmentavailability&APIToken=OTI4MjI%3D-eiBNyIvyQA8%3D&propertyCode=p0494361');
$results = json_decode($pullData);
//Table columns
echo '<table>
<tr>
<th>Apartment Name </th>
<th>Beds</th>
<th>Baths</th>
<th>Floor Plan Name</th>
<th>Minumum Rent</th>
<th>Maximum Rent</th>
</tr>';
//Iterate throught the API data and return only required columns
foreach($results as $formatted_results){
echo '<tr>';
echo '<td>'.$formatted_results->ApartmentName.'</td>';
echo '<td>'.$formatted_results->Beds.'</td>';
echo '<td>'.$formatted_results->Baths.'</td>';
echo '<td>'.$formatted_results->FloorplanName.'</td>';
echo '<td>'.$formatted_results->MinimumRent.'</td>';
echo '<td>'.$formatted_results->MaximumRent.'</td>';
echo '</tr>';
}
echo '</table>';
?>
a simple get will do it.
$.get("data.php", function(data){ // GET data from page "data.php"
$("#result").html(data); // display data in a div with id "result"
});
Consider if your index.html contains below code then you can call ajax call in your script of html file. Here it is working code (consider index.html and date.php both are at the same place)
index.html
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="result">
</div>
</body>
</html>
<script type="text/javascript">
$(document).ready(function(){
$.get( "data.php", function( data ) {
$( ".result" ).html( data );
});
});
</script>
And data.php file contain code as given by you
data.php
<?php
$pullData = file_get_contents('https://api.rentcafe.com/rentcafeapi.aspx?requestType=apartmentavailability&APIToken=OTI4MjI%3D-eiBNyIvyQA8%3D&propertyCode=p0494361');
$results = json_decode($pullData);
//Table columns
echo '<table>
<tr>
<th>Apartment Name </th>
<th>Beds</th>
<th>Baths</th>
<th>Floor Plan Name</th>
<th>Minumum Rent</th>
<th>Maximum Rent</th>
</tr>';
//Iterate throught the API data and return only required columns
foreach($results as $formatted_results){
echo '<tr>';
echo '<td>'.$formatted_results->ApartmentName.'</td>';
echo '<td>'.$formatted_results->Beds.'</td>';
echo '<td>'.$formatted_results->Baths.'</td>';
echo '<td>'.$formatted_results->FloorplanName.'</td>';
echo '<td>'.$formatted_results->MinimumRent.'</td>';
echo '<td>'.$formatted_results->MaximumRent.'</td>';
echo '</tr>';
}
echo '</table>';
?>
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();
}
})
I've made a combobox based on the database.
I want when I've selected one combobox and instantly display the appropriate table combobox that I choose.
Example when I choose west java table will show bandung and bogor.
this my controller
public function show() {
$data['provinsi'] = $this->mdl_onchange->get_provinsi();
$data['kota'] = $this->mdl_onchange->get_kota();
$this->load->view('form_onchange', $data);
}
this my model
function get_provinsi() {
$query = $this->db->get('table_provinsi');
return $query->result();
}
function get_kota() {
$query = $this->db->get('table_kota');
return $query->result();
}
this is my view
<p>
<label for="select_provinsi"></label>
<select name="select_provinsi" id="select_provinsi">
<option>--Pilih Provinsi--</option>
<?php foreach($provinsi as $row_provinsi) { ?>
<option value="<?php echo $row_provinsi->id_provinsi?>">
<?php echo $row_provinsi->nama_provinsi; ?>
</option>
<?php } ?>
</select>
</p>
<table border="1" name="select_kota" id="select_kota" style="border-
collapse:collapse; width:60%;">
<tr style="background:yellow;">
<th>Id kota</th>
<th>Id provinsi</th>
<th>nama kota</th>
</tr>
<?php foreach($kota as $c){?>
<tr>
<td>
<?php echo $c->id_kota; ?>
</td>
<td>
<?php echo $c->id_provinsi; ?>
</td>
<td>
<?php echo $c->nama_kota; ?>
</td>
</tr>
<?php } ?>
</table>
my jquery
<script type ="text/javascript">
$("#select_kota").chained("#select_provinsi");
</script>
I've made like this but its data always appear when I have not chosen combobox western Java.
it is
I see you are using chained Jquery. That's for chaining two selects, not for a table.
For this, the best approach you could get is to perform an Ajax call to get the table rows and modify the table tbody inner HTML.
First, you need to modify the model get_kota() function, to select only the kota on a provinsi, by it's id_provinsi:
function get_kota($id_provinsi) {
$this->db->where('id_provinsi', $id_provinsi);
$query = $this->db->get('table_kota');
return $query->result();
}
After that, create a new function on your controller to return the new values via Ajax. Here I'll include also the modification to the original method to remove the first call for kotas:
public function show() {
$data['provinsi'] = $this->mdl_onchange->get_provinsi();
$this->load->view('form_onchange', $data);
}
public function ajax_getkotas($id_provinsi) {
$kotas = $this->mdl_onchange->get_kota($id_provinsi);
foreach ($kotas as $kota) {
echo '<tr>\n';
echo '<td>' . $kota->id_kota . '</td><td>' . $kota->id_provinsi . '</td><td>' . $kota->nama_kota . '</td>\n';
echo '</tr>\n';
}
}
Now, let's go back to your view. Let's divide it into three parts: the select, the table and the jquery.
You can keep your select as it is right now.
The table will be empty at first, you can maybe have something like this:
<table border="1" name="select_kota" id="select_kota" style="border-
collapse:collapse; width:60%;">
<thead>
<tr style="background:yellow;">
<th>Id kota</th>
<th>Id provinsi</th>
<th>nama kota</th>
</tr>
</thead>
<tbody>
<tr><td>Please, select a provinsi from the above dropdown to display results</td></tr>
</tbody>
</table>
And now let's go for the JQuery Ajax call:
$('#select_provinsi').on('change', function() {
$.ajax({
type: 'GET',
url: "<?php echo site_url('your_controllername/ajax_getkotas') ?>" + "/" + $('#select_provinsi').val() , // we call our new function with the selected id
dataType: "html",
success: function (data) { // change the data from our response
$('#select_kota tbody').html(data); //rows are printed inside the tbody of our table
},
failure: function(err) {console.log("Error on the Ajax call");} // Some error feedback just in case. You can check network XHR to see what's going on.
});
})
With this I think you can get it working. Let me now it that's works for you or we need to change anything.
I have an array of rows, each with a radio button with the same name (name='status'). I have put the radio buttons into an index so that each radio button will reflect its correct value. However, the javascript no longer works to change the value - I am stumped with the corresponding changes I need to make to the javascript.
<form action="<?php echo $this->form_action; ?>" method="post">
<p class="hide"><input name="status" type="text" value="" /></p>
<table id="manage-items" cellpadding="0" cellspacing="0" border="0">
<thead>
<tr>
<th><?php echo $this->translate('Item');?></th>
<th><th><?php echo $this->translate('Status');?></th></th>
</tr>
</thead>
<tbody>
<?php $ind = 0; ?>
<?php foreach ($this->items as $item) {
$item_link = 'type=product';
?>
<tr id="item_<?php echo $ind; ?>">
<td data-label="Title"><span class="orangelink"><?php echo $item->title; ?></span></td>
<td align="left" style="padding-left:22px" class="color-status-<?php echo $item['active']; ?>">
<?php if (in_array($item['active'], array(0, 1))) { ?>
<input type="radio" name="item[<?php echo $ind; ?>][status]" value="1" <?php if ($item['active'] == 1) echo 'checked'; ?>>Active
<br>
<input type="radio" name="item[<?php echo $ind; ?>][status]" value="0" <?php if ($item['active'] == 0) echo 'checked'; ?>>Inactive
<?php } else { ?>
<?php echo $item['active']; ?>
<?php } ?>
</td>
</tr>
<?php $ind++; ?>
<?php } ?>
</tbody>
</table>
</form>
<script type="text/javascript">
//console.log(jQuery)
head.ready('jquery', function () {
$(document).ready(function () {
$('input[name="radio"]').click(function () {
var status = this.value;
var id = $(this).parents('tr').attr('id');
console.log('here now')
$.ajax({
type: 'post',
url: "?module=items&controller=block&action=modDaStatusBro",
data: 'id=' + id + '&status=' + status,
beforeSend: function () {
$('#' + id).animate({
'backgroundColor': '#FFBFBF'
}, 400);
},
success: function (result) {
if (result == 'ok') {
$.get(window.location.href, function (data) {
$('#' + id).html($(data).find('#' + id).html());
setTimeout(function () {
$("#" + id + "").animate({'backgroundColor': 'transparent'}, 400).find('.tooltip').simpletooltip();
deletePage();
}, 500);
});
} else {
alert(result);
$("#" + id + "").animate({'backgroundColor': 'transparent'}, 400);
}
}
});
});
});
});
</script>
Table data elements generated in PHP between
<tr id="<?php echo $item['id']; ?>">
....
</tr>
do not appear to contain input elements named "status". The HTML generated for each value of $ind is expected to be
<input type="radio" name="item[n][status]" .... Active
<input type="radio" name="item[n][status]" .... Inactive
where n is the value of $ind. But the selector in
$('input[name="status"]').click(function () {
doesn't match the name format. A one key stroke solution would be to to add a * wild card to the selector to match "status" anywhere in the name value:
$('input[name*="status"]').click(function () {
Other possibilities exist such as adding a special class name to each radio button affected (not recommended), or add a special data attribute to each radio input to be found by query selector (feasible).
Footnote: DIV elements surrounding TR elements should not be there. DIV is not listed as a permitted child element of TBODY elements, nor a permitted parent object of TR elements.
(Answer to comment)
A jQuery plugin is needed for color animation of properties, e.g. backgroundColor.
Code can be downloaded from CDNs at
https://code.jquery.com/color/jquery.color-2.1.2.min.js , or
https://cdnjs.cloudflare.com/ajax/libs/jquery-color/2.1.2/jquery.color.min.js
or the entire package can be downloaded from GitHub
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 );
}
});
}