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']);
Related
Background Information
I have some PHP / HTML / JavaScript code that loads a web form. For discussion purposes, let's say this form is the "edit widget details" page.
This form contains a table... with a bunch of rows. Each row has one drop down box - the same one for each row - and the selected value of the drop down is determined based on previously saved data in the database.
Problem
The drop down lists are not being populated by the .append() call that I'm making and I don't know why.
Code
Here's the sequence of events in my logic:
PHP logic - loops through each record that needs to be included in the table... and creates an EMPTY box like so:
for ($i=0; $i < count($w_details['tc']); $i++) {
....
//logic to build basic table structure including:
echo "<td><select placeholder='Domain:' name='domain" .$i ."' id=domain" .$i ."'></select></td>";
echo "<input type='hidden' class='domainvals' id='hidden_domain" .$i . "' name='hidden_domain" .$i. "' value='" .$wdetails['tc'][$i]['destdomain'] . "'/>";
...
}
Then once the page is finished rendering, I have this logic in my document.ready section:
//populate domain list.
$.ajax({
url:"<?php echo site_url('domain/domainlist');?>",
type:'POST',
dataType:'json',
success: function(res) {
//loop through results
var htmlstring = "<option value='' disabled selected>Select the Domain</option>";
for (var key in res) {
if (res.hasOwnProperty(key)) {
htmlstring += "<option value=" + res[key]['domain'] + ">" + res[key]['domain'] + "</option>";
}
}
//find every hidden input that is storing a domain value
$('.domainvals').each(function (i, row) {
console.log($(this).val()) ;
$('#domain'+i).append(htmlstring);
//TODO: add logic to select the right value using $this.val();
});
},
error: function(xhr, req, err) {
//var err = eval("(" + xhr.responseText + ")");
console.log(err.Message);
}
});
What I've Tried so far:
In the F12 debug window, I've verified that I have a "domain0" control like this:
$("#domain0").find('option')
No error messages appear (just the empty array / list) so I definitely have created it. I can also see the controls on the form.
I tried to change my code that appends the html to hard code the name, like so:
$('#domain0').append(htmlstring);
Again, no errors, but it doesn't populate the list.
Any suggestions would be appreciated. I'm sure it's something simple that I'm just missing.
You can append an option using Javascript/Jquery like this:
$('myDropDown').append($('<option>', {
value: optionValue,
text: optionText
}));
If you are adding those domain
$("#domain(n)")
elements dynamically, then you cannot just access them like
$("#domain0")
do
$(document).find("#domain0") or $("body").find("#domain0")
instead.
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 trying to make user interface to edit/insert records and i'm having some troubles with my code.
Lists the records :
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
$html.="<tr>
<td style>{$row['name']}<input type='hidden' id='id' value='$row[a_id]'></td>
<td>{$row['season']}</td>
<td><a href='edit1/new' id='edit'></a></td>
<tr style='height: 5px;'></tr>
</tr>..
Now the js that i`m having trubles with:
<script type='text/javascript'>
$('#edit').on( 'click', function () {
var x = document.getElementById('id').value;
$.ajax({
type: 'post',
url: 'insert_edit.php',
data: {
id: x
},
success: function( data ) {
console.log( data );
}
});
});
</script>
inside the insert_edit.php
if(isset($_POST['id'])){
$html = Edit();
}else{
$html = Add();
}
For some reason the on click function doesnt seem to work and it doesnt posts datainsert_edit.php`
Any help will be apriciated thank you.
NOTE: I'm not sure even if the posts works I'm using the Java Script the right way since my while loop prints it foreach ID and my guess is even it if it posts the data it will aways posts the value of the first record.
Try this- on click function replace with this-
$(document).on("click", "#edit", function(){
// ..
})
I managed to fix it. Here is how I did it:
I made an array $urlparts wich is my permalinks.
The button code goes like this
..a href='/account/competitions/edit1/update/$row[a_id]'>Edit..
And some php
if (isset($urlparts[4]) && is_numeric($urlparts[4])){
require_once ("insert_edit.php");
$html = Edit();
}
and inside the Edit();
just snach the id with
$id = $urlparts[4];
Thank you for the feeedback guys. Made me realize that I`m looking at the issue from the wrong angle:)
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.
Hi I'm trying dynamically remove database entries using JS and AJAX without refreshing whole page.
Here is my data.php file:
<?php
require_once('db.php');
if (isset($_GET['list'])) {
$query = "SELECT * FROM message";
mysql_query("SET NAMES 'UTF8'");
$qq=mysql_query($query);
$i = 1;
echo '<div id="rezult">';
while($ff = mysql_fetch_array($qq)){
echo '<div id="id'.$ff['id'].'">'.$i++.'. Name: '.$ff['name'].' Message:'.$ff['message'].'</div>';
}
echo '</div>';
}
?>
With this code I'm retrieving a data from mysql table:
index.php
function list() {
$.get('data.php?list=1', function(o) {
$('#list').html(o);
});
}
How to dynamically delete desired entry without refreshing a page?
tried to add this code below as a link to the entry, but it getting cut javascript:$.post( like that.
<a href="javascript:$.post('delete_post.php', { id: '$ff[id]' } );" class='delete_post' title='delete post'>delete post</a>
Thanks for advices
Be careful!, if someone make a call to your php file data.php?list=ANYNUMBER he will be able to delete any row, be sure you are using security tools to avoid that.If you use ajax and Jquery I think it will be easier.
try something like this:
$.ajax({
type: "POST",
url: "list.php",
data: { list: "1", session_id: session_ID }
}).done(function( msg ) {
alert( "Data deleted: " + msg );
});
where session_id is the value of the field (in your example is 1), session_id is when someone go to your page you assign him a SESSION_ID, after he click the delete button, you compare if the session ID that you assign is equal to the the session_id from the server (you avoid people from another site to call your list.php). If session_id from the ajax is equal to session session_id on the server allow to delete take a look to this: PHP Session Security