Table does not disappear on AJAX call - javascript

I am trying to remove to this table on successful delete from an AJAX to PHP call.
Below is the function ,
list.php
<script type="text/javascript">
function massDelete()
{
if (!confirm("Are you sure"))
{
return false;
}
else
{
var selecedids = $("#selectedids").val();
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("success").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "ajax_delete.php?massDelete=" + selectedids.value, true);
xhttp.send();
}
}
return false;
}
</script>
the above code successfully gives me the selected ID for deletion
on this PHP side which is on another File
ajax_delete.php
<?php
if (!empty($_REQUEST['massDelete'])) {
$selectId = $_REQUEST['massDelete'];
$finalId = ltrim($selectId, ",");
$sql = mysql_query("delete from contact_form where contactUser_id in ($finalId)", $con);
if ($sql) {
// echo '<script>';
//echo 'var parent = document.getElementById("fullTable")';
//echo 'element.remove(parent)';
//echo '</script>';
echo "sucess deleted";
} else {
echo "Please select a Contact to delete";
}
}
?>
The response does give me the successful message, but somewhere I want to disappear the below HTML table in response
list.php
<?php
echo '<table id="fullTable">';
echo "<tr><td> ";
echo '<input type="checkbox" name="checkAll" id="checkAll"/></td>';
echo '<td colspan="8" align="right">';
echo '<button type="submit" onClick="return massDelete()" name="delete" class="deleteall" id="deleted">Delete All</button></td>';
echo "</tr>
<tr>
<th></th>
<th>FIRST NAME</th>
<th>LAST NAME</th>
<th>EMAIL</th>
<th>PHONE</th>
<th>FAX</th>
<th></th>
<th></th>
<th></th>
</tr>";
while ($row = mysql_fetch_array($results)) {
echo '<div id="checkboxlist">';
echo '<tr class="show">';
echo '<td><input name="checkbox[]" type="checkbox" class="checkbox1" value="' . $row['contactUser_id'] . '" id="Checkbox1"></td>';
echo '<td>' . $row['first_name'] . '</td>';
echo '<td>' . $row['last_name'] . '</td>';
echo '<td>' . $row['email'] . '</td>';
echo '<td>' . $row['phone'] . '</th>';
echo '<td>' . $row['fax'] . '</td>';
echo '<td>Edit</td>';
echo '<td><a class="delete" href="#" id="' . $row['contactUser_id'] . '">Delete</a></td>';
echo '<td>View</td>';
echo '</div>';
}
} else {
echo '<td colspan="9"><h1>No contacts found.</td></h1>';
}
?>
I am confused to what should I do so that if one row is deleted than only that row disappears,
but if all the checkboxes are selected for deletion, than on sucess, tha whole table should disappear..

So it sounds like the php successfully deletes it since when you refresh the page the correct data shows up.
But if the page has to be refreshed for it to show up properly, you need to make sure you are returning the correct information, and parsing it correctly. Just console.log() the response xhttp.responseText, and see if the correct data is returned, and then double check you are parsing it correctly (changing the dom appropriately).

You don't need to refresh your page to show it's correct. You need to use javascript to remove the row on success. Here's the basics:
var deletedRow = $('#fullTable');
$.post('script.php', {data:data}, function(){
if(data == "success"){
deletedRow.remove(); //This will remove the row from the view
}
});
Ajax can return a call and you give a statement that shows if success, you have to have javascript actually delete it. Yes, we know it's removed from the database, so you can successfully remove the view from the page.
UPDATE This is using jQuery, not pure javascript. But it's only an example to show that you need to delete the element using javascript and it won't just disappear because it's not in your database anymore.

Finally after referring to this remove any element using Jquery
I found the solution, and I also changed the AJAX function code which is mentioned below,
function massDelete()
{
var element = $(this);
var selecedids = $("#selectedids").val();
var info = 'massDelete=' + selectedids.value;
if(confirm("Are you sure you want to delete this?"))
{
$.ajax({
type: "POST",
url: "ajax_delete.php",
data: info,
success: function(){
}
});
$this.parent("#fullTable").load("list.php");
}
return false;
}
the $this.parent("#fullTable").load("list.php"); statement reloaded that table hence reflecting only those information which are present in the database.

Related

Execute AJAX from Main file after previously inserting data through AJAX

I have a questions for which I need some help.
I have a page which, after it is finished loading, executes an AJAX, creates a table in PHP containing 2 buttons: 1 change password, the other is delete. Once the table is complete it is injected into a div in the main file. That works great so far. Now after that table is loaded, I want to be able to call another AJAX function linked in the JS file in the main page. So I have 3 components:
1. <div id="DbInfo"></div>
That is where I add the information from the users.
my php which executes the code and gets the information from my database.
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT LoginName FROM table";
$res = mysqli_query($conn, $sql);
if (mysqli_num_rows($res) > 0) {echo "<center>";
echo "<table border='1'>";
echo "<tr>";
echo "<td>User</td>";
echo "<td colspan=2 align=center>Available Functions</td>";
echo "</tr>";
while($row = mysqli_fetch_assoc($res)) {
echo "<tr>";
echo "<td>" . $row['User'] . "</td>";
echo "<td><button type='button' class='smallbutton' id='removeUser' value='" . $row['LoginName'] . "'>Delete User</button></td>";
echo "<td><button type='button' class='smallbutton' id='CPW' value='" . $row['LoginName'] . "'>Change Password</button></td>";
echo "</tr>";
}
echo "</table>";
echo "</center>";
} else {
echo "";
}
mysqli_close($conn);
And lastly the AJAX which does the injection of the created table into the HTML:
$(document).ready(function(){
$.ajax({
method: "POST",
url: "UserData.php",
success: function(data){
//document.getElementById("DbInfo").innerHTML = data;
document.getElementById("DbInfo").html(data);
}
});
});
Again, these functions are working fine. What I want to do after the page is done, be able to click one of these injected buttons and execute another AJAX. Unfortunately the standard declaration that I use for AJAX does not work.
$(document).ready(function(){
$("#removeUser").click(function(){
The question: How can I make sure after the table is injected, that I can call an AJAX function which is linked as an external source (<script src="script.js"></script>) in the main document?
Thanks for your help.
try :
$('#DbInfo').on('click', 'button[id="removeUser"]', function(i,e){
console.log('remove :' + $(this).val());
});

ajax not firing on change to contenteditable cell

I have a contenteditable table which when edited should update a table in the database via ajax but nothing is happening to the database when I change the values.
<div id="activities2" class="activities2"> <?
$q2a="SELECT activityid, activitynumber, title, description, leaders, time FROM activities where activities.meetingid='$id' AND activities.unitid='$input2'";
$r2a=mysqli_query($dbc,$q2a) or die(mysqli_error($dbc));
echo "<table class='layouttable'><tr><td>ActivityNumber</td><td>Title</td><td>Description</td><td>Leaders</td><td>Time</td><td>Edit</td>";
while($row2a
=mysqli_fetch_assoc($r2a))
{
echo "
<tr>
<td contenteditable='true' id='activitynumber:" . $row2a['activityid'] . "'>" . $row2a['activitynumber'] . "</td>
<td contenteditable='true' id='title:" . $row2a['activityid'] . "'>" . $row2a['title'] . " </td>
<td contenteditable='true' id='description:" . $row2a['activityid'] . "'>" . $row2a['description'] . " </td>
<td contenteditable='true' id='leaders:" . $row2a['activityid'] . "'>" . $row2a['leaders'] . " </td>
<td contenteditable='true' id='time:" . $row2a['activityid'] . "'>" . $row2a['time'] . " </td>
</tr>.
";
}
echo"</table>"; ?><br><Br></div>
The javascript for ajax is:
<script name = 'inlineedit'>
$(document).ready(function(){
$("td[contenteditable=true]").blur(function(){
var msg = $(".alert");
var newvalue = $(this).text();
var field = $(this).attr("id");
$.post("activityupdate.php",field+"="+newvalue,function(d){
var data = JSON.parse(d);
msg.removeClass("hide");
if(data.status == '200'){
msg.addClass("alert-success").removeClass("alert-danger");
}else{
msg.addClass("alert-danger").removeClass("alert-success");
}
msg.text(data.response);
setTimeout(function(){msg.addClass("hide");},3000);//It will add hide class after 3 seconds
});
});
});
</script>
and the php file doing the editing (though it doesnt seem to be getting this far is:
<?
$response = NULL;
$status = http_response_code(406);
if(!empty($_POST)){
include "connect_db.php"; //Including Database Settings
foreach($_POST as $key=>$value){
$key = strip_tags(trim($key));
$value = strip_tags(trim($value));
$explode = explode(":",$key);
$activity_id = $explode[1];
$field_name = $explode[0];
if(isset($activity_id)){
$query = "UPDATE activities SET $field_name='{$value}' WHERE activityid='$activity_id'";
$update = mysqli_query($dbc,$query) or die(mysqli_error($dbc)); //Update the activity Table
if($update){
$response = "User Details Updated";
http_response_code(200); //Setting HTTP Code to 200 i.e OK
}else{
$response = "Not Modified";
http_response_code(304); //Setting HTTP Code to 304 i.e Not Modified
}
}else{
$response = "Not Acceptable";
}
}
}
echo json_encode(array(
"status"=>$status,
"response"=>$response
));
?>
You would need few changes in code:
Instead of setting contenteditable='true' use class='editable'.
in the js try using on change instead of blur.
$("td.editable").on ("change",function(){....
this would execute ajax on every change in the editable fields.

Form in a PHP inside auto-refresh DIV tag won't work

I have the following two pages. The index.php includes purchases_pending.php through PHP. The first time the page loads the form works perfectly but when the DIV(#pp) is refreshed after 10 seconds the FORM does not work. Is there a solution for this? Or if I can do it through AJAX, can somebody help me with the code. As you have seen my codes you'll probably know Im a beginner.
Thanks in advance.
index.php
<script type="text/javascript">
function update(){
$('#pp').load('/status/purchases_pending.php');
}
setInterval( update, 10000 );
</script>
<div class="content">
<div class="content_left">
<p>
<h3>Pending Purchases</h3>
<div class="user_content"><div id="pp"><?php include ($purchases_pending); ?></div></div>
</p>
purchases_pending.php
<?php
$CONFIG = $_SERVER["DOCUMENT_ROOT"]. "/config/";
include($CONFIG. "pages.php");
include($db);
$sql = "SELECT * FROM account WHERE status='Pending' AND type='Purchase'";
$query = mysqli_query($conn, $sql);
if (mysqli_num_rows($query) > 0) {
echo '<table>';
echo '<tr> <th align="left">Party</th> <th>Box</th> <th>Rate</th> <th>Status</th> </tr>';
while ($result = mysqli_fetch_assoc($query)) {
$id = $result['id'];
$party = $result['party'];
$box = $result['box'];
$rate = $result['rate'];
$amount = $result['amount'];
echo '<form action="" method="post">';
echo '<tr>';
echo '<td>' . $party . '</td>';
echo '<td align="center">' . $box . '</td>';
echo '<td align="right">' . $rate . '</td>';
echo '<td align="center"><input type="checkbox" name="status[]" id="status[]" value="' . $id . '" /></td>';
echo '</tr>';
}
echo '</table>';
echo '<input type="submit" name="submit" value="Completed" class="input" />';
echo '</form>';
}
else {
echo 'Hooray...No pending purchases';
}
if(isset($_POST['submit']) && $_POST['submit']!="") {
$status = $_POST['status'];
$count = count($_POST['status']);
for($i=0;$i<$count;$i++) {
$update_purchases = "UPDATE account SET status='Completed', user_confirm='$user_confirm' ,user_confirm_time=current_timestamp WHERE id='$status[$i]'";
$query_purchases = mysqli_query($conn, $update_purchases);
}
header ('location:/');
}
?>
load the JS function outside the jquery
<script>
function update(){
$('#pp').load('/status/purchases_pending.php');
}
</script>
$( document ).ready(function() {
setInterval( update, 10000 );
});
JS load needs to be in document ready in order to work.
Short hand is
$(function() {
var update = function() {
$('#pp').load('/status/purchases_pending.php');
setTimeout(update, 10000);
}
update();
});
Move this code to index.php as this no longer exist in the page because it gets removed when replacing div #pp
if(isset($_POST['submit']) && $_POST['submit']!="") {
$status = $_POST['status'];
$count = count($_POST['status']);
for($i=0;$i<$count;$i++) {
$update_purchases = "UPDATE account SET status='Completed', user_confirm='$user_confirm' ,user_confirm_time=current_timestamp WHERE id='$status[$i]'";
$query_purchases = mysqli_query($conn, $update_purchases);
}
To explain php renders from the server as html, it reads top to bottom.
So when the js inserts it, it is not inserting the code, but rather the rendering of the code.
Ajax is used to send data, but on load no data is being sent other than give me a form.
The post doesn't exist because it is already rendered. When using an include it is "inserted" as part of the code to be executed and thus works.

How to let user hide rows from a html table

I have a table which gets dynamically populated by the results of a search query:
echo '<table class="table">';
if ($num==0) echo "<tr><td>Sorry, no items found.</td></tr>";
else {
echo '<tr> <th>Nr.</th> <th>Name</th>';
echo '<th>Description</th> <th>Image</th>';
$lf = 1;
while ($dsatz = mysql_fetch_assoc($res))
{
echo '<tr>';
echo "<td>$lf</td>";
echo '<td>' . $dsatz["name"] . '</td>';
echo '<td>' . $dsatz["description"] . '</td>';
echo '<td><img src="' . $dsatz['image'] . '" style="height:100px; width:auto" /></td>';
echo '</tr>';
$lf = $lf + 1;
}
}
echo '</table>';
The result is a table of items. Now what I would like to do is give the user the possibility to hide any row by a single click or, if not possible, by checking boxes and hiting a second Hide(delete) button at the and of the table. The rows must not be deleted from the database only hidden from view.
Any ideas how I could do this?
Thx
Seb
///////////////////////////// EDIT ////////////////////////////////////////////
Thx for the Input!
Here is what worked for me:
In table:
echo "<td><input type='checkbox' name='hide_cand' style='float:right' id='hide_cand' onclick=' return hideRow(this)'/></td>";
script:
function hideRow(checkbox)
{
if(confirm('This action can not be undone, are you sure you want to delete this item from the list?'))
{
checkbox.parentNode.parentNode.style.display = "none";
return true;
}
return false;
}
Thx for your help!
Basically, you want something like this:
$('.table').on('click','tr',function(){
$(this).hide();
});
If you wish to add checkbox inside each row:
$('.table').on('change','tr :checkbox',function(){
$(this).closest('tr').hide(); //no need here to check for checkbox state
});
Think the far most easy would be :
$('.table tr').click(function() {
$(this).hide();
});
Try something like this
$("#tableID").delegate("td", "click", function() {
$(this).closest("tr").hide();
});

Display data in tabular manner in PHP form

I want to do something like this..
I have a update form in PHP, which contains around 15 fields,
I want to show some data in tabular manner while you open the page for update..
Senario:
If you want to update a record of a person on day to day basis, I have the feature with me to search out that person form database, and when you click on update data..
it should show in a manner that,
field1.....----------
field2.....----------
field3.....----------
and now,
for field4,5,6,7
if these fields contain the data then show in a table manner with fields 4,5,6,7 as coloums and no of rows depending upon the number of entries (should be non editable)(assume the case of multiple input)
then form will continue.
field4.....--------
field5.....--------
field6.....--------
field7.....--------
typically these field(4,5,6,7) gets their value update frequently and I have to maintain the previous inputs also.
help me out with some solution, as I am unable to figure out how to do this?
before that i was using this.. here i was having a form field which can generate 5 options, and will populate the fields with data if u have entered before, now i want to change the display as I don't want user to play with the old data, so I want to show old data into a table and enter new data via a simple text field,
as their is no point to keep these multiple input form field as user is updating only one value at a time.
<script>
function Submitted_Date(value,object)
{
value = document.getElementById("subdate_num").value;
if (value > -1) {
var input= new Array(value);
var p;
//alert("Enter The fields You Know ");
var ele = document.getElementById("subdate");
if(ele.hasChildNodes())
{
var len = ele.childNodes.length;
while(ele.childNodes.length - value > 1)
{
ele.removeChild(ele.lastChild);
}
}
for (var i=len-1;i<value;i++)
{
p= i+1;
input[i] = document.createElement('div');
input[i].innerHTML = 'Submitted_Date' + p + ': <input type="text" value="" name="subdate' + p + '" id="subdate' + p +'" size = 25 onclick="javascript: showCalendar("Submitted_Date'+ p +'")"/>';
document.getElementById("subdate").appendChild(input[i]);
var subdate = 'subdate' + p;
}
}
document.getElementById("subdate1").focus();
}
</script>
<tr>
<td> Submitted Date :
<select name="subdate_num" id="subdate_num" onChange="return Submitted_Date(this.value,this.form)">
<?php
for ($i=0;$i<=5;$i++)
{
if ($i==0) { $temp = "<option value=$i> - </option>"; echo $temp; }
else { $temp = "<option value=$i>$i</option>";
echo $temp; }
}
?>
</select></td>
</tr>
</table>
<table>
I think this is what you want, this will show the information in a table with as many (or few) columns as you want
$query = "SELECT * FROM announcements ORDER BY announceid";
$result = mysql_query($query);
echo "<table border='1'>
<tr>
<th>Announcement ID</th>
<th>Announcement Name</th>
<th>Announcement Category</th>
<th>Approved?</th>
<th></th>
</tr>";
if ($result && mysql_num_rows($result) > 0) {
$x = 0;
while ($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['announceid'] . "</td>";
echo "<td>" . $row['title'] . "</td>";
echo "<td>" . $row['category_name'] . "</td>";
echo "<td>" . $row['status'] . "</td>";
echo '<td>Edit</td>';
echo "</tr>";
$x ++;
};
echo "</table>";
Let me know if that is what you are looking for, or if there is any other way I can help. Thanks!

Categories

Resources