I'm trying to create a add/delete/edit post system using php for a website. I have the add working, so when the user enters in information it gets added to the database and then asynchronously gets added onto the page using ajax. I want a similar function that deletes asynchronously as well. Right now, when I click delete, only the oldest post gets deleted AFTER refreshing the page. It does not delete the post as soon as I click the delete button which is my goal. This is what I have so far. The home.php is where my form is that collects the information and also prints out the information from the database. handledelete.php is where the deleting is handled.
home.php
<script>
$(function() {
$('#deleteButton').click(function(event) {
event.preventDefault();
$.ajax({
type: "GET",
url: "handle_delete.php",
data : { entry_id : $(this).attr('data-id') },
beforeSend: function(){
}
, complete: function(){
}
, success: function(html){
$("#show_entries").append(html);
}
});
});
});
</script>
<div id="entry">
<form method="GET" action="handle_insert.php">
<table align="center" width="30%" border="0">
<tr>
<td><input type="text" name="activity" id="activity" placeholder="Activity" required /></td>
</tr>
<tr>
<td><input type="text" name="duration" id="duration" placeholder="Duration (hours)" required /></td>
</tr>
<tr>
<td><input type="text" name="date" id="date_" placeholder="Date (YYYY-MM-DD)" required /></td>
</tr>
<tr>
<td><button type="submit" name="submitButton" id="submitButton">Add input</button></td>
</tr>
</table>
</form>
</div>
<!-- shows the previous entries and adds on new entries-->
<div id="show_entries">
<?php
$userID = $_SESSION["user"];
$link = mysqli_connect('localhost', 'oviya', '', 'userAccounts');
$query="SELECT * FROM dataTable WHERE user_id='$userID'";
$results = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="output" >';
$entry_id = $row["entry_id"];
$output= $row["activity"];
echo "Activity: ";
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8')."<br>"."<br>";
$output= $row["duration"];
echo "Duration: ";
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8')." hrs"."<br>"."<br>";
$output= $row["date_"];
echo "Date: ";
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8')."<br>"."<br>";
echo '<button type="submit" name="deleteButton" data-id='.$entry_id.' id= "deleteButton">Delete</button>';
//echo '<button type="submit" name="editButton" data-id='.$entry_id.' id="editButton">Edit</button>';
echo '</div>';
}
?>
</div>
handle_delete.php
session_start();
$user = 'oviya';
$password = '';
$db = 'userAccounts';
$host = 'localhost';
$port = 3306;
$link = mysqli_connect($host, $user, $password, $db);
mysqli_query($link,"GRANT ALL ON comment_schema TO 'oviya'#'localhost'");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if(!empty($_GET["entry_id"])){
$entry_id = mysqli_real_escape_string($link, $_GET["entry_id"]);
$sql = "DELETE FROM dataTable WHERE entry_id = '$entry_id'";
$result = mysqli_query($link, $sql);
die();
mysqli_close($link);
}
This line is the problem. It would add elements if your AJAX call were returning HTML, which it isn't:
$("#show_entries").append(html);
Instead, you want to remove the deleted element, which you can reference directly and remove from the DOM:
$('#deleteButton').click(function(event) {
event.preventDefault();
// Get a reference to the whole row element.
var row = $(this).parent();
$.ajax({
type: "GET",
url: "handle_delete.php",
data : { entry_id : $(this).attr('data-id') },
success: function(html){
// Remove the row
row.remove();
}
});
});
Related
I want to rerun a PHP File which was loaded in a div in my HTML code. On my main page, I have a form and a table. The form adds rows to the MySQL table, and the table on the page outputs that MySQL table. I want the table on the HTML page to update when the new row is added via the form, without refreshing the page. I tried putting the load command in the success part of the ajax function for my form but that didn't work. I looked at many other answers and none worked for me.
This is my code
redeem.php
<h1>Rewards</h1>
<form id="add-reward-form" action="" method="POST">
<label for="inputRewardDescription" class="form-label">Enter Reward Description</label>
<input type="text" id=inputRewardDescription name="description" class="form-control" required>
<label for="inputRewardCost" class="form-label">Enter Reward Cost</label>
<input type="text" id=inputRewardCost name="points" class="form-control" required>
<button type="submit" class="btn btn-success" id="submit-btn">Save</button>
</form>
<p id="message"></p>
<div id="sql-table">
<?php include 'tables.php'; ?>
</div>
tables.php
<?php
$host = "";
$user = "";
$pass = "";
$db_name = "";
//create connection
$connection = mysqli_connect($host, $user, $pass, $db_name);
//test if connection failed
if(mysqli_connect_errno()){
die("connection failed: "
. mysqli_connect_error()
. " (" . mysqli_connect_errno()
. ")");
}
//get results from database
$result = mysqli_query($connection,"SELECT RewardName, PointsRequired FROM rewards");
$all_reward = array(); //declare an array for saving property
while ($reward = mysqli_fetch_field($result)) {
// echo '<th scope="col">' . $reward->name . '</th>'; //get field name for header
array_push($all_reward, $reward->name); //save those to array
}
// echo ' </tr>
// </thead>'; //end tr tag
echo '<table class="table">
<thead>
<tr>
<th scope="col">Reward</th>
<th scope="col">Points Required</th>
<th scope="col">Edit</th>
<th scope="col">Delete</th>
</tr>
</thead>';
//showing all data
while ($row = mysqli_fetch_array($result)) {
echo "<tbody>
<tr>";
foreach ($all_reward as $item) {
echo '<td>' . $row[$item] . '</td>'; //get items using property value
}
echo '<td><i class="fas fa-edit"></i></td>';
echo '<td><i class="fas fa-trash"></i></td>';
echo ' </tr>
</tbody>';
}
echo "</table>";
?>
redeem-form.js
$(document).ready(function() {
$("#add-reward-form").submit(function(e) {
e.preventDefault();
$.ajax( {
url: "add_rewards.php",
method: "POST",
data: $("form").serialize(),
dataType: "text",
success: function(strMessage) {
$("#message").text(strMessage);
$("#add-reward-form")[0].reset();
$("#sql-table").load(" #sql-table > *");
}
});
$("#sql-table").load(" #sql-table > *");
});
});
The form works perfectly fine with ajax, and submits to the database without refreshing. But I would like to update the table on my page as well without reloading.
$("#sql-table").load(" #sql-table > *");
This is what I tried. I placed it inside the success function and the submit function but both did not work.
You are mis-using $.load(). It's a shorthand for $.ajax(). The first argument must be a URL. Optional arguments are data and options.
You are passing it a selector, so the request fails. As-is, $("#sql-table").load(" #sql-table > *"); is attempting an AJAX request to the URL /%20#sql-table%20%3E%20*. (!)
Simply change the selector for the PHP file you want to execute:
$("#sql-table").load("tables.php");
How about forcing redeem.php to re-evaluate the PHP div every time a change happens to the inputs?
<h1>Rewards</h1>
<script>
function redrawSQLTable(){
document.getElementById('sql-table').innerHTML = "<?php include 'tables.php'; ?>"
}
</script>
<form id="add-reward-form" action="" method="POST">
<label for="inputRewardDescription" class="form-label">Enter Reward Description</label>
<input type="text" id=inputRewardDescription name="description" class="form-control" required onchange="redrawSQLTable()">
<label for="inputRewardCost" class="form-label">Enter Reward Cost</label>
<input type="text" id=inputRewardCost name="points" class="form-control" required onchange="redrawSQLTable()">
<button type="submit" class="btn btn-success" id="submit-btn">Save</button>
</form>
<p id="message"></p>
<div id="sql-table">
<?php include 'tables.php'; ?>
</div>
I want to create a column that has a text box inside each table row. The user can write any text inside the text box and click the 'Save' button to save it in the database. Additionally, the text box can be edited unlimited times. My code is the following:
index.php
<?php
...
while($row = $result->fetch_assoc()){
echo "<form action= 'search.php' method='post'>";
echo "<form action='' method='get'>";
echo "<tr>
<td><input type='checkbox' name='checkbox_id[]' value='" . $row['test_id'] . "'></td>
<td> ".$row['test_id']." </td>
<td><input type='text' name='name' value='<?NOT SURE WHAT TO INCLUDE HERE ?>'/></td>
<td><input type='submit' value='Save' id='" . $row['test_id'] . "' class='name' /></td>
<td> ".$row['path']." </td>
<td> ".$row['video1_path']." </td>
<td> ".$row['video2_path']." </td>
<td> ".$row['video3_path']." </td>
<td> ".$row['video4_path']." </td>";
if(empty($row["directory"])){
echo "<td></td>";
}else {
echo "<td><div><button class='href' id='" . $row['test_id'] . "' >View Report</button><div></td>";
}
echo " <td style='display: none;'> ".$row['directory']." </td>
</tr>";
}
?>
</table> <br>
<input id= 'select_btn' type='submit' name='submit' value='Submit' class='w3-button w3-blue'/>
</form>
</form>
</div>
<!-- Opens the pdf file from the pdf_report column that is hidden -->
<script type="text/javascript">
$(document).on('click', '.href', function(){
var result = $(this).attr('id');
if(result) {
var dir = $(this).closest('tr').find("td:nth-child(9)").text();
window.open(dir);
return false;
}
});
</script>
<!-- Updates text input to database -->
<script type="text/javascript">
$(document).on('click', '.name', function(){
var fcookie1= 'mycookie1';
var fcookie2= 'mycookie2';
var name = $(this).attr('id');
if(name) {
var text1 = $(this).closest('tr').find("td:nth-child(2)").text();
var text2 = $(this).closest('tr').find("td:nth-child(3)").text();
document.cookie='fcookie1='+text1;
document.cookie='fcookie='+text2;
$.ajax({
url: "name_edit.php",
type:"GET",
success: function() {
// alert("Edited Database");
}
});
}
});
</script>
name_edit.php
<?php include 'dbh.php' ?>
<?php include 'search.php' ?>
<?php
if (isset($_COOKIE["fcookie1"]))
echo $_COOKIE["fcookie1"];
else
echo "Cookie Not Set";
if (isset($_COOKIE["fcookie2"]))
echo $_COOKIE["fcookie2"];
else
echo "Cookie Not Set";
$var1 = $_COOKIE["fcookie1"];
$var2 = $_COOKIE["fcookie2"];
$conn = mysqli_connect($servername, $username, $password, $database);
$sql = "UPDATE test_data SET name='$var2' WHERE id='$var1'";
$query_run= mysqli_query($conn,$sql);
if($query_run){
echo '<script type="text/javascript"> alert(Data Updated)</script>';
} else {
echo '<script type="text/javascript"> alert(Data Not Updated)</script>';
}
?>
My idea was for the user to write any text. Then i will 'grab' the text and its expected id and save it to a cookie, when the save button is clicked. The cookie will then be echoed in name_edit.php and insert it in the sql code which will then update my database.
Im not sure what to include in 'value' inside the form tag. If there is data inside the database then display it inside the text box which can also be edited, else display blank for a text to be inserted.
I am new to coding and I'm a bit confused if my idea is correct or should i approach it another way.
I did some research and found out i did not have to use form but instead use 'contenteditable'. To edit the specific column i changed
<td><input type='text' name='name' value='<?NOT SURE WHAT TO INCLUDE HERE ?>'/></td>
<td><input type='submit' value='Save' id='" . $row['test_id'] . "' class='name' /></td>
to this:
<td class='name' data-id1='" . $row['test_id'] . "' contenteditable='true'>".$row['name']."</td>
and for my jquery i added the following:
<style>
.editMode{
border: 1px solid black;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
// Add Class
$('.name').click(function(){
$(this).addClass('editMode');
});
// Save data
$(".name").focusout(function(){
$(this).removeClass("editMode");
var id = $(this).closest('tr').find("td:nth-child(2)").text();;
var value = $(this).text();
$.ajax({
url: 'name_edit.php',
type: 'post',
data: { value:value, id:id },
success:function(response){
alert('Edits Saved');
return false;
}
});
});
});
</script>
and in the php side, i simply did the following:
<?php include 'dbh.php' ?>
<?php
$conn = mysqli_connect($servername, $username, $password, $database);
$field = $_POST['field'];
$value = $_POST['value'];
$id= $_POST['id'];
$sql = "UPDATE test_data SET name='".$value."' WHERE test_id='".$id."'";
mysqli_query($conn,$sql);
echo 1;
?>
I am trying to run a form that stores an Id in a hidden input tag so that I can retrieve it in the next page using php. For some reason I can't retrieve the value using the php file. Echoing orderId.value and order number are working fine.
main_page.php
<script>
function EditValues(orderNumber) {
var orderId = document.getElementById("orderId");
orderId.value = orderNumber;
document.forms["form1"].submit();
}
</script>
<body>
<form action="edit-form.php" id="form1">
<div class="container">
<!--use the hidden input variable to save the order number clicked -->
<input id="orderId" type="hidden" name="orderId"/>
<?php
require("config.php");
$con = new mysqli(DB_Host, DB_User, DB_Password, DB_Name);
if ($con->connect_error) {
die("Connection failed");
}
echo '<table id="tblOrders" name ="OrderTable" style="width: 100%">
<tr>
<th>Sno</th>
<th>Order Number</th>
</tr>';
$displayTableDataQuery = "SELECT id, orderNumber, customerName, deliveryDate FROM orderTable";
if ($tableData = $con-> query($displayTableDataQuery)) {
while($row = $tableData-> fetch_assoc()) {
$id = $row['id'];
$orderNumber = $row["orderNumber"];
echo '<tr >
<td>'.$id.'</td>
<td id = "orderNumber">'.$orderNumber.'</td>
<td><input type = "button" id ="editButton'.$id.'" value = "Edit" onclick = "EditValues('.$orderNumber.');"/> </td>
<td><input type = "button" id = "printInvoice'.$id.'" value="Print" onclick = "PrintInvoice('.$orderNumber.');" /> </td>
</tr>';
}
} else {
echo $con->error;
}
$tableData->free();
?>
</div>
</form>
</body>
In edit-form.php
<?php
$xyzabc = $_POST['orderId'];
echo $xyzabc;
?>
There is nothing echoed for $xyzabc
I would prefer if there was some way to do this without jQuery as I'm kind of new to this and haven't really gotten a hang of how everything works together as of now.
You can store value directly to the hidden input field.
<!--use the hidden input variable to save the order number clicked -->
<input id="orderId" type="hidden" name="orderId" value="<?=$variable_name;?> />
So that when you submit the form
<?php
$xyzabc = $_POST['orderId'];
echo $xyzabc;
?>
will fetch the data.
Or you can pass the hidden value in url. For example
<a href="localhost:8000/edit-form.php?orderId="<?=$variable_name;?>
Then in you form-edit.php
<?php
$xyzabc = $_GET['orderId'];
echo $xyzabc;
?>
I want to create delete feature using function and jquery
My jquery works and show messages but nothing happen "Nothing Deleted"
Jquery Code
<script type="text/javascript">
$(".remove").click(function(){
var id = $(this).parents("tr").attr("id");
if(confirm('Are you sure to remove this record?'))
{
$.ajax({
url: 'delete.php',
type: 'GET',
data: {id: id},
error: function() {
alert('Something is wrong');
},
success: function(data) {
$("#"+id).remove();
alert("Record removed successfully");
}
});
}
});
PHP Function Code
function delete($table,$id) {
global $connect;
mysqli_query($connect, "DELETE FROM `$table` WHERE `id` = $id ");
}
Delete.php Code
include ('function.php');
$id = $_GET['id'];
$table = 'msg';
delete($table,$id);
HTML Code
<table class="table table-striped" style="background-color: #ffffff;">
<tr>
<th>ID</th>
<th>From</th>
<th>Title</th>
<th>Date</th>
<th>Action</th>
</tr>
<?php
$i = '1';
$username = $user_data['username'];
$query = "SELECT * FROM msg WHERE `go_to` = '$username' Order by id";
$result = mysqli_query($connect, $query);
while($row = mysqli_fetch_assoc($result))
{
?>
<tr>
<td><?php echo $i++; ?></td>
<td><?php echo $row['come_from']; ?></td>
<td>
<a href="read_message/<?php echo $row['id']; ?>"><?php if(count_msg_not_opened($username, $row['id']) > '0')
{
echo $row['title'];
}
else
{
echo '<b>' . $row['title'] . '</b>';
} ?></a></td>
<td><?php echo $row['date']; ?></td>
<td>
<button class="btn btn-danger btn-sm remove">Delete</button>
</td>
</tr>
<?php } ?>
</table>
I also include "jquery.min.js"
When I press "Delete" bottom this message appears "Are you sure to remove this record?"
I pressed "Yes" then this message appears "Record removed successfully", but nothing was deleted.
I don't know where the problem is.
You forgot to add the id attribute to the <tr>
<tr id="<?php echo $row['id']; ?>">
You should also add error checking and prepared statements to your PHP code.
Are you sure that you have connected your PHP-code to your SQL-database?
function delete($table,$id) {
global $connect;
mysqli_query($connect, "DELETE FROM `$table` WHERE `id` = $id ");
}
The code above is relying on a connection already existing within your PHP-file. See this to find out how to apply a connection.
I had a problem with my auto-fill input form, with PHP MySQL and jQuery of course. So I have the select option form and some 'disabled' textboxes. And I want when I select the one of the option, the textboxes is auto-fill with value from the database
So there is my whole code :
PHP (Database connection) - I put it above my <html> code
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'db_mydatabase';
mysql_connect($host, $user, $pass);
mysql_select_db($db);
$user = '';
$query = mysql_query("SELECT * FROM tb_payment") or die (mysql_error());
?>
HTML
<select name="student" class="input-data">
<option value="">-- SELECT STUDENT --</option>
<!-- Do loop data from database -->
<?php while ($row = mysql_fetch_object($query)): ?>
<option value="<?php echo $row->id_user ?>">
<?php echo $row->name ?>
</option>
<?php endwhile; ?>
</select>
<br />
<table border=1>
<tr>
<th>ID</th>
<td><input type="text" class="output-id" disabled /></td>
</tr>
<tr>
<th>Name</th>
<td><input type="text" class="output-name" disabled /></td>
</tr>
<tr>
<th>Total Payment</th>
<td><input type="text" class="output-total" disabled /></td>
</tr>
</table>
jQuery :
$(document).ready(function(){
$(".input-data").on("change", function(){
<?php $id_user = "$(this).val()"; ?>
<?php $data = mysql_query("SELECT * FROM tb_payment WHERE id_user = '$id_user'") or die (mysql_error()); ?>
<?php while($row = mysql_fetch_object($data)): ?>
$(".output-id").val(<?php $row->id_user ?>);
$(".output-name").val(<?php $row->name ?>);
$(".output-total").val(<?php $row->total ?>);
<?php endwhile; ?>
});
});
But when i try to select the option, the values are wouldn't appear. Can someone help me?
What about creating new page name process.php contain:
require_once "connectDB.php";
header('Content-type: application/json; charset=utf-8');
if(isset($_POST['one'])){
$json = array();
$id = trim($_POST['one']);
$query = "SELECT id, name, total FROM tb_payment WHERE id_user = ?";
$statement = $databaseConnection->prepare($query);
$statement->bind_param('s', $id);
$statement->execute();
$statement->bind_result($nId, $nName, $nTotal);
while ($statement->fetch()){
$user=array('id'=>$nId,'name'=>$nName,'total'=>$nTotal);
array_push($json,$user);
}
echo json_encode($json, true);
}
And the Jquery:
$(document).ready(function(){
$(".input-data").on("change", function(){
var id = $(".input-data").val();
var data = 'one=' + id;
$.ajax({
type: "POST",
url: "process.php",
data: data,
dataType: 'json',
success: function (data) {
if (data) {
for (var i = 0; i < data.length; i++) { //for each user in the json response
$(".output-id").val(data[i].id);
$(".output-name").val(data[i].name);
$(".output-total").val(data[i].total);
} // for
} // if
} // success
}); // ajax
});
});
You have to print
$(".output-id").val(<?php print $row->id_user ?>);
$(".output-name").val(<?php print $row->name ?>);
$(".output-total").val(<?php print $row->total ?>);