I am using a PHP function to format any 2D PHP array to HTML table, In that table I need to add a delete button in each row, So when the user clicks the delete button jQuery should take particular fields ( 3 fields ) and submit in a php file and it should give the response without reloading the page, I have several dynamic tables in same PHP files, So i have used $table_name as the form ID to differentiate the FORMS, and In the del.php ( Where my form get submitted ) I decide which table should I look up to delete the row using the PRIMARY KEY. My Problem is Do I have to create Forms Within each table to do this task? or can I simply put some fields and submit the form using jQuery?
Any help would be much appreciable .
function formatArrayToTable($foo, $deletable = 0, $restaurant_id ='', $table_name = '') {
//open table
echo '<table class="imagetable">';
// our control variable
$first = true;
foreach($foo as $key1 => $val1) {
//if first time through, we need a header row
if($first){
echo '<tr>';
foreach($val1 as $key2 => $value2) {
echo '<th>'.$key2.'</th>';
}
if($deletable) {
echo "<th>'Delete'</th>";
}
echo '</tr>';
//set control to false
$first = false;
}
echo '<tr>';
foreach($val1 as $key2 => $value2) {
echo '<td>'.$value2.'</td>';
}
if($deletable) {
$primary = $val1["id"];
echo "<input type='hidden' name='table_name' value='{$table_name}' />";
echo "<input type='hidden' name='restaurant_id' value='{$restaurant_id}' />";
echo "<td><input class='delete_class' type=\"button\" name=\"delete_id\" value={$primary} onclick='SubmitForm($table_name)'/></td>" ;
}
echo '</tr>';
}
echo '</table>';
}
My Javascript Function
function SubmitForm(formId){
var message = "";
$("#"+formId+" input").each(function() {
message += $(this).attr("name");
});
$.ajax({
type: "POST",
url: "del.php",
data: message,
success:
function() {
$('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>Entry is Deleted </p>")
.hide()
}
});
}
-Regards
Your question seems to ask if you can remove items from a DB using just jQuery. Conventionally, as far as I know, this is not doable, because your DB is server-side and your jQuery is client-side. That being said, I am sure some kook has created a library for it. Despite that, to answer your actual question:
You need to know how you can use jQuery to simulate direct removal of a table row from a DB table. Here is a rough example of your needed jQuery, a sample output of your current php function, and something that should live in del.php to handle the actual delete.
Example Table
Quick notes. Add thead and tbody tags to help browsers with the displaying. Remove the onclick="" bit, you are using jQuery, so just add your callbacks with a JavaScript block. Make sure your code adds the `.submittable' class (or other descriptive name) to your table. You could wrap the whole table in a form, then use a plugin like jquery form to handle submissions of each form, but that seems like overkill for only handful of fields, so I will explain how to do it with the raw materials.
<table class="imagetable submittable">
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>file</th>
<th>meta</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type='hidden' name='table_name' value='secret_image_table' />
<input type='hidden' name='restaurant_id' value='123' />
<input class='delete_class' type='button' name='delete_id' value="Delete" />
</td>
<td>Silly Cat Image</td>
<td>yarny-cat.jpg</td>
<td>{"submitter":"De Zéro Toxin"}</td>
</tr>
</tbody>
</table>
jQuery code block
It is a terrible idea to submit your table name from any client-side form, ajax or otherwise. That is super sensitive information, and any programmer/hacker could use that knowledge to their advantage when trying to attack your site. Despite that, I don't know the usage of this, so it may be fine in your setting. Still bad practice though.
// any time any element with the 'delete_class' on it is clicked, then
$(document).on('click', '.delete_class', function(e) {
var row = $(this).closest('tr');
var data = {
table: $('[name="table_name"]').val(),
id: $('[name="restaurant_id"]').val()
};
$.post('del.php', data, function(r) {
// do some special stuff with your json response 'r' (javascript object)
...
// do what you showed us you are doing, displaying a message
$('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>Entry is Deleted </p>")
.hide();
// remove the row, since it is gone from the DB
row.remove();
}, 'json');
});
del.php
Again, table_name on submission = bad-idea. Horse beaten.
// define a delete function that accepts a table name an id
// define some functions to sanitize your $_POST data, to prevent SQL Injection.
// run said functions before you get to this point
// json response function, since you said you want a response from your js
function respond($data) {
echo #json_encode($data);
exit;
}
if (empty($_POST)) respond(array('error' => 'Invalid request'));
$table_name = $_POST['table_name'];
$id = $_POST['id'];
$response = deleteRecord($table_name, $id);
if ($response == $what_you_expect_on_a_successful_delete) {
// create a response message, in associative array form
$message = array('success' => true);
// add some other information to your message as needed
$message['sideNote'] = 'I like waffles.';
// respond with your message
respond($message);
}
// if we got this far your delete failed
respond(array('error' => 'Request Failed'));
Hope this helps.
If you really want to use jQuery to delete a row in a DB directly, you will need to establish a DB connection from jQuery. Not such a bright idea. Instead, you should have a server side function to do the job and call that function using an AJAX call from jQuery.
Related
I'm working on a project, and I have an issue. First, let me present a few things to you.
Database
An example on what the database structure looks like
ID | NAME
1 | Daniel
2 | David
HTML / PHP script
What the page itself looks like
<?php
$allUsers = mysqli_query($db,"SELECT * FROM users");
echo "<table class=\"table table-hover\" style=\"width: 100%;\">
<thead>
<tr>
<th scope=\"col\">#</th>
<th scope=\"col\">Username</th>
</tr>
</thead>
<tbody>";
while($row = mysqli_fetch_array($allUsers))
{
echo "<tr>";
echo "<th class=\"inner\">" . $row['id'] . "</th>";
echo "<td>" . $row['username'] . "</td>";
echo "</tr>";
}
echo "
</tbody>
</table>";
?>
Javascript code
The Javascript code as found on this website as well
$(function () {
$(".inner").dblclick(function (e) {
if($(event.target).attr('class')!="thVal")
{
e.stopPropagation();
var currentEle = $(this);
var value = $(this).html();
updateVal(currentEle, value);
}
});
});
function updateVal(currentEle, value) {
$(document).off('click');
$(currentEle).html('<input class="thVal" type="text" value="' + value +
'"
/>');
$(".thVal").focus();
$(".thVal").keyup(function (event) {
if (event.keyCode == 13) {
$(currentEle).html($(".thVal").val());
}
});
$(document).click(function () {
if($(event.target).attr('class')!="thVal")
{
$(currentEle).html($(".thVal").val());
$(document).off('click');
}
});
}
Now the first thing I'd like to ask: This does not seem to work on my php page. On my html page on the other hand, where I tried this as well, it does work. What am I doing wrong?
When we've fixed that, how could I make sure that when my user double clicks a value, and changes it, that it updates in the database as well. So, for example, if a user of mine double clicks the value "David" and sets it to "Jeremy", the database will be update to Jeremy as well.
First of all, you should distinguish server script and client/ browser script. PHP is server script, when you run this file, it will be compiled to html file. Javascript/ jquery is browser script, it just runs on html file.
If you want when my user double clicks a value, and changes it, that it updates in the database as well. You should add more code in javascript/ query:
$(".thVal").keyup(function (event) {
if (event.keyCode == 13) {
$(currentEle).html($(".thVal").val());
// add code here
// submit the value to server to update database
}
});
"This does not seem to work on my php page. On my html page on the
other hand, where I tried this as well, it does work"
"if a user of mine double clicks the value "David" and sets it to
"Jeremy", the database will be update to Jeremy as well."
Actually both question are related to the same problem. When changing your value with JS you're changing your HTML (front only) but by reloading you'll get the value you had at first... If you want to change your database you'll have to use AJAX as said Litvak. Could be something like this...
if (event.keyCode == 13) {
var name = $(".thVal").val();
var id = // you need to get the ID to be able to change your database at the right row
$.ajax({
type: 'POST',
data: {
id : id,
name : name
}
url: 'changeName.php',
dataType: 'html',
success:function(data, text) {
// If change in database worked, do this...
$(currentEle).html(name);
}
error : function(request, status, error) {
// There was a problem, couldn't change database, do this...
}
});
}
and your changeName.php would be where you run your sql script to change the database...
function changeName($id, $name) {
// make your checks here and your sql call
}
changeName($_POST['id'], $_POST['name']);
I have a html table that is generated VIA PHP and data in a database, what I want to do is have a button in the last cell of each row that says edit and when you click that button the text in the other cells becomes textboxes or other types of input fields so that you can edit them and then press submit which would send that form off to be updated in the database. The code I have right now to generate the table is:
<table style="width:100%; " class = "table table-striped table-bordered table-hover">
<tr>
<th>Name</th>
<th>Status</th>
<th>Description</th>
<?php
if($_SESSION['editGroup'] != 0){
echo "<th>Edit</th>";
}
?>
</tr>
<?php
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$checkQuery = "SELECT userGiven, userStatus, userDesc FROM user_Status WHERE organization = 'myOrg' ORDER BY userGiven ASC";
$prepared = $dbh->prepare($checkQuery);
$prepared->execute();
$data = $prepared->fetchAll(PDO::FETCH_ASSOC);
foreach($data as $row){
echo "<tr>";
if($_SESSION['editGroup'] != 0){
echo "<td width='20%'>" . $row['userGiven'] . "</td><td width='10%'>" . $row['userStatus'] . "</td><td width='70%'>" . $row['userDesc'] . "</td><td width='10%'><button type='button' class='btn btn-info'>Edit</button></td>";
}else{
echo "<td width='20%'>" . $row['userGiven'] . "</td><td width='15%'>" . $row['userStatus'] . "</td><td width='75%'>" . $row['userDesc'] . "</td>";
}
echo "</tr>";
}
?>
</table>
What I am trying to do is change the cell with userStatus to a drop down field with the current value as the starting value and the other value in/out as the other value to select between.
I also want to change the userDesc to a textarea and I think I know how to do all this but I am running into a problem conceptually when I try to apply it to the dynamic table.
What I was thinking was that I could use jquery/javascript to get the innerhtml of span variable that could surround those two cells and then change the html to the various input fields containing the current text allowing the user editing them to change those values.
How do I do this for this sort of problem though, I would need onClick events for all the buttons and I wouldn't know how many buttons there would be, that's based off of the number of rows in the table.
That would result in hundreds of lines of redundant code so I assume there has to be a much better way. Anyone know what a way to accomplish this? I found this: http://stackoverflow.com/questions/16202723/how-to-edit-data-onclick which is close to what I want but that seems to be static values where I want to be able to do this for any of the rows in the table.
In your for loop, you'll want to put something identifiable in the <tr> and <td> elements. I'd personally go with a data-attribute. For example:
Echo Row Code
foreach($data as $row){
echo "<tr data-row='{$row[id]}'>";
if($_SESSION['editGroup'] != 0){
echo "<td width='20%' data-column='name'>" . $row['userGiven'] . "</td><td width='10%' data-column='status'>" . $row['userStatus'] . "</td><td width='70%' data-column='description'>" . $row['userDesc'] . "</td><td width='10%'><button type='button' class='btn btn-info'>Edit</button></td>";
}else{
echo "<td width='20%'>" . $row['userGiven'] . "</td><td width='15%'>" . $row['userStatus'] . "</td><td width='75%'>" . $row['userDesc'] . "</td>";
}
echo "</tr>";
}
So, as you can see I've added a data-row attribute to <tr> which should get the value of the database record's ID. Change it as necessary - I made the assumption it'd be named 'id'. Also, I added the data-column attribute to <td> which should identify each column for us. This is all the modification needed in the PHP.
Now, here's what the JQuery for the edit button looks like:
Front-End Event Listener: Part 1
$( function(){
$(document).on("click", ".btn-info", function(){
var parent = $(this).closest("tr");
var id = $(parent).attr("data-row");
var name = $(parent).children("[data-column='name']");
var status = $(parent).children("[data-column='status']");
var desc = $(parent).children("[data-column='description']");
var nameTxt = $(name).html();
var statusTxt = $(status).html();
var descTxt = $(desc).html();
$(name).html("<input name='name' data-dc='name' value='" + nameTxt + "'>");
$(status).html("<input name='status' data-dc='status' value='" + statusTxt + "'>");
$(desc).html("<textarea name='desc' data-dc='description'>" + descTxt + "</textarea>");
$(this).replaceWith("<button class='btn-info-save'>Save</button>");
});
}
Finally, we need to define what happens upon hitting save (the above example changes the "edit" button into a "save" button). That could be anything, but we'll assume it'll be an AJAX call:
Front-End Event Listener: Part 2
$( function(){
$(document).on("click", ".btn-info-save", function(){
var parent = $(this).closest("tr");
var id = $(parent).attr("data-row");
var data = {id: id};
$("[data-dc]").each( function(){
var col = $(this).attr("data-dc");
var val = $(this).val();
data[col] = val;
});
$.ajax({
url: "/dynamic-edit/edit.php", // Change this to your PHP update script!
type: 'POST',
dataType: 'json',
data: data,
success: function(ret){
//Do Something
console.log(ret.response);
},
error: function(ret){
console.log(ret.response);
}
});
});
}
Now, in your PHP script that handles the AJAX request:
PHP Code for 'edit.php'
$name = $_POST['data_name'];
$status = $_POST['data_status'];
$description = $_POST['data_description'];
// Do whatever with the data
// Output JSON - get the response in JS with ret.response
// either inside the success or error portion of the AJAX
echo json_encode( ["response"=>"Row edited successfully."] );
This is a very simple example, but it gets the point across. Be sure to change the AJAX url from "/dynamic-edit/edit.php" to wherever you'll make your PHP script that will actually make the updates after submitting.
You'll likely want to do cleanup after a successful edit; for example, changing the text boxes back to just text in a <td>. Also, please note that I just changed them to textboxes. I know you said in your post you wanted to make one the status a dropdown and the description a textarea, but this example should be easy enough to change. I don't know what the values of the dropdown should be, so you'll have to do that part.
Notes
I went with $(document).on("click" ... instead of $(".btn-info").on("click" ... because whenever you're dealing with dynamic content, you always want the event listener on the document, not the element. Why? Because if you click the "edit" button, it disappears and a "save" button appears, you now lose that event listener forever. If you were to re-add the "edit" button (say, after a successful save), that button would need the event listener added again. When you go the route of attaching the event listener to the document, however, you can remove/add all you want and it'll still work.
You can add 'data' attribute to each button with the user id that you want to update. For example:
<button data-iduser='<?= $use["id"] ?>' class='btn btn-info'>Edit</button>
$("btn btn-info").click( function() {
var idUser = $(this).attr("data-iduser");
// some ajax if you want with that iD
});
I have two sheets. The control displays a list of job details that also contains a column that echos the notes on the active job, and the other sheet is where the operator can attach a note.
What I need to do is alert the user on the control page that the note for a job has been changed, which would happen after the operator submits the note.
Currently, I have a cell that highlights red when there is a note present, but want to actively send an alert when there is a new note.
I've tried an onChange() function but it wouldn't alert until I made an input field and changed it myself on the control page. I also tried the .change function but that didn't work either.
The query sent from the operator page to the SQL database is:
UPDATE operations
SET notes=$notes
WHERE jobID=$jobID
AND operation=$operation"
The code to echo the red cell on the control page is this PHP:
$conN = mysqli_connect(DB_HOST, DB_USER);
if (!$conN) {
die('Could not connect: ' . mysqli_error($conN));
} // Check Connection
mysqli_select_db($conN,"jms");
$jid = $row['jobID'];
$opn = $row['operation'];
$highlight = mysqli_query($conN,
"SELECT notes FROM operations WHERE jobID=$jid AND operation=$opn"
);
while ($data = mysqli_fetch_array($highlight))
if (isset($data['notes']) && $data['notes'] != "") {
echo "<td id='notes' style='background-color:red;width:1%;'>" .
"<input class='target' type='text' value='" .
$data["notes"]. "' >" . "</td>";
} else {
echo "<td style='background-color:white;width:1%;'>" . "</td>";
}
echo "</tr>"; // End the row
$index++;
While the cell that is being echo'd as red has an if (isset()) function to display red if there is a note in the database for the specific job and operation.
EDIT:
Here is the Javascript I've been trying to call with the onChange function:
function newNote() {
var jobID = "X";
var operation = "Y";
alert("New note added to Job No. "+jobID+" at Operation No. "+operation);
}
As you can see, its a very simple piece of script, so I ended up just simplifying the process and using a simple alert of text as a test.
you can do it by JQuery or JavaScript , what you need is to immediately detect any change of DB records by sending request and then receiving response .
use ajax function by either jQuery or java script and make the post target your mentioned control page , and alert the response.
one example by jquery :
$(document).ready(function(){
$.ajax({
type: "POST",
url: "yourcontrolpage",
data: { jid: jid ,opn:opn},
success: function(html) {
alert(html);
}
}); });
for example , you can retrieve the number of records or the latest record , so in the next request you can determine whether there is a change so alert will be executed or there is no change so nothing will be happened
I'm working on a MySQL update form and struggle to make a drop down selectbox that will autofill the rest of the form with data from mysql. Basically its a table that consist of users and their credentials. When updating a second table with this form i want to be able to select the username from a drop menu and let that selection autofill the rest of the credentials before moving on to the rest of the form.
Here is some of the code for setting up the select and input:
<?php
//DB Connect
...
// Get array of users
$select_users = "SELECT * FROM users";
if (!mysql_query($select_users)) {
die('Error: ' . mysql_error());
} //all good so far
$select_users_result = mysql_query($select_users);
?>
<select id="selectbox" name="navn" onchange="populateData(this.value)">
<option>USER</option>
<?php
$klubb = array();
$klasse = array();
while ($row = mysql_fetch_array($select_users_result, MYSQL_ASSOC)) {
echo "<option value='" . $row['navn'] . "'>". $row['navn'] ."</option>";
//echoing these vars will output all rows for the column specified...
$klubb[] = $row['klubb'];
$klasse[] = $row['klasse'];
}
mysql_close();
?>
</select>
<tr>
<td>Klubb: </td>
<td><input id="klubb" type="text" name="klubb" class="cred_input" />
</td>
</tr>
<tr>
<td>Klasse: </td>
<td><input id="klasse" type="text" name="klasse" class="cred_input" /> </td>
</tr>
And then some javascript
<script>
function populateData()
{
//alert('in populateData');
y = document.getElementById("selectbox");
document.getElementById("klasse").value = [y.selectedIndex];
document.getElementById("klubb").value = [y.selectedIndex];
}
</script>
The result here is a number in the <td>klubb and <td>klasse based on my selection in the drop menu.
How can i connect the arrays with that index number in the javascript so that it will show the actual data from the array ?
I've been seeking an answers for a few days now but can't find anything that answers my question.
Thanks for any help!
Well you can use AJAX for that.
For a tutorial on how to use AJAX and PHP script with Mysql This can help you.
First you need to create a PHP script that will gather the data you need for filling up the forms.
Setup the AJAX to be triggered everytime you choose something in your Drop Down List and pass its value on the PHP script you created.
On your AJAX script configure it to call the PHP script you created for retrieving the data (a value will be thrown in this script based on your drop down list).
Once you receive a response from your AJAX call just use a simple Javascript to fill up the forms based on the data your received.
Another tip is to use JQuery since it is easier for you to setup your AJAX request.
Use AJAX here.
In the populateData() function, use ajax to send the request to retrieve the user credentials & through Javascript, populate your textboxes with the retrieved values.
You could echo the two php arrays as javascript objects, and then access those in your populate function (this is the quick solution). But a better way is to ajax in the actual data
<script>
var klasse = <?=json_encode($klasse)?>
var klubb = <?=json_encode($klubb)?>
</script>
Well you can use Ajax. Make this as your form.
<?php
//DB Connect
...
// Get array of users
$select_users = "SELECT * FROM users";
if (!mysql_query($select_users)) {
die('Error: ' . mysql_error());
} //all good so far
$select_users_result = mysql_query($select_users);
?>
<select id="selectbox" name="navn" onchange="populateData(this.value)">
<option>USER</option>
<?php
$klubb = array();
$klasse = array();
while ($row = mysql_fetch_array($select_users_result, MYSQL_ASSOC)) {
echo "<option value='" . $row['navn'] . "'>". $row['navn'] ."</option>";
//echoing these vars will output all rows for the column specified...
$klubb[] = $row['klubb'];
$klasse[] = $row['klasse'];
}
mysql_close();
?>
</select>
<div id="some_container">
</div>
Your AJAX request :-
<script type="text/javascript">
$('select').on('change', function() {
var selectedVal = this.value; // or $(this).val()
$(document).ready(function() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "file.php?selectedVal="+selectedVal,
dataType: "html", //expect html to be returned
success: function(response){
$("#some_container").html(response);
}
});
});
});
</script>
file.php
<?php
echo '
<tr>
<td>Klubb: </td>
<td><input id="klubb" type="text" name="klubb" class="cred_input" value="$phpValueHere"/>
</td>
</tr>
<tr>
<td>Klasse: </td>
<td><input id="klasse" type="text" name="klasse" class="cred_input" value="$phpValueHere> </td>
</tr>';
?>
In your file.php, get the value of selectedVal via $_GET['selectedVal'] and then extract data from table, after extracting echo the data in those input boxes.
I have created a HTML table using a echoing each row in a by looping through the rows of the database which is stored into the PHP fetch array function after retrieving from the database using the SELECT statement. Along with this I added another column which is a submit button hence it looped through every each row.
I did this so that I could get the "ID" of each row when submitted and run another script using AJAX JQUERY. But the problem is that my javascript code only gets the value of the first row when submited and it is unresponsive to the other rows.
Table code:
<form id="mainform">
<table>
<th>ID</th>
<?php
$result = mysql_query("SELECT * FROM test");
while ($row = mysql_fetch_array($result)) {
$ID = $row['ID'];
echo "<td><input type='hidden' id='hiddenfield' value='$ID'></td>";
echo "<td><input type='submit' value='select' /></td>";
}
?>
</table>
</form>
Javascript:
$("#mainform").on("submit", function(){
$("#testdiv").empty();
$.get("boom.php", { ID: $("#hiddenfield").val() },
function(data) {
$("#newdiv").append(data);
});
});
</script>
With this AJAX code I am trying to get the value to boom.php where now I am just testing if the correct value has been parsed.
Anyone can help me out? I am stuck...
There are two problems: first, you can't reuse the same id on multiple fields. They must be unique. Use a class:
echo "<td><input type='hidden' class='hiddenfield' value='$ID'></td>";
even then, .val() will only return the first matching item's value.
Assuming you want to pass a list of ID values, you'll need to build the list yourself:
$("#mainform").on("submit", function(){
$("#testdiv").empty();
var vals = [];
$('.hiddenfield').each(
function() {
var field = $(this);
vals.push(field.val());
}
);
$.get("boom.php", { ID: JSON.stringify(vals) },
will pass a string version of the list (e.g. ["1","2","3"]);
If you want to send each ID separately, do so within the each loop:
$('.hiddenfield').each(
function() {
var field = $(this);
$.get("boom.php", { ID: field.val() },
}
);