Sorry for the constant question!! I have a table that displays records of data from my database. To make life easier, I have make it editable using jquery so that a user can click right an area an edit right away without redirecting to a different page.
A couple of questions.. how can i refine the below code so that when an area on the table with checkboxes and links is clicked, it will not respond/not editable?
Also, the editing function does not fully work at the moment and im having problems trying to figure out where the problem is. The table responds to everything defined in the jquery below but does not update my database.
There is my jquery code edit.js
$(function() {
$('tbody').on('click','td',function() {
displayForm( $(this) );
});
});
function displayForm( cell ) {
var column = cell.attr('class'),
id = cell.closest('tr').attr('id'),
cellWidth = cell.css('width'),
prevContent = cell.text()
form = '<form action="javascript: this.preventDefault"><input type="text" name="newValue" value="'+prevContent+'" /><input type="hidden" name="id" value="'+id+'" />'+'<input type="hidden" name="column" value="'+column+'" /></form>';
cell.html(form).find('input[type=text]')
.focus()
.css('width',cellWidth);
cell.on('click', function(){return false});
cell.on('keydown',function(e) {
if (e.keyCode == 13) {//13 == enter
changeField(cell, prevContent);//update field
} else if (e.keyCode == 27) {//27 == escape
cell.text(prevContent);//revert to original value
cell.off('click'); //reactivate editing
}
});
}
function changeField( cell, prevContent ) {
cell.off('keydown');
var url = 'edit.php?edit&',
input = cell.find('form').serialize();
$.getJSON(url+input, function(data) {
if (data.success)
cell.html(data.value);
else {
alert("There was a problem updating the data. Please try again.");
cell.html(prevContent);
}
});
cell.off('click');
}
And in my edit.php I have the following:
<?php
include ("common.php");
if (isset($_GET['edit'])){
$column = $_GET['column'];
$id = $_GET['id'];
$newValue = $_GET["newValue"];
$sql = 'UPDATE compliance_requirement SET $column = :value WHERE ComplianceID = :id';
$stmt = $dbh ->prepare($sql);
$stmt->bindParam(':value', $newValue);
$stmt->bindParam(':id', $id);
$response['success'] = $stmt->execute();
$response['value']=$newValue;
echo json_encode($response);
}?>
and finally my html..
<div class="compTable">
<table>
<thead><tr><th>Compliance Name</th><th>Compliance Goal</th><th>Compliance Description</th><th>Opions</th><th>Invite</th></tr></thead>
<tbody>
<?php
$sql = 'SELECT * FROM compliance_requirement';
$results = $db->query($sql);
$rows = $results->fetchAll();
foreach ($rows as $row) {
echo '<tr id="'.$row['ComplianceID'].'">';
echo '<td class="crsDesc">'.$row['ComplianceName'].'</td>
<td >'.$row['ComplianceGoal'].'</td>
<td >'.$row['ComplianceDescription'].'</td>
<td ><a href =inviteObstacle.php?action=invite&id=name1> InviteObstacle </a></td>
<td style="text-align: center; vertical-align: middle;"> <input type="checkbox" name="query_myTextEditBox">
</td>';
echo '</tr>';
}?>
</tbody>
</table>
</div>
Your help is much appreciated. thanks in advance
Simplest solution for identifying editable cells would be give those cells a class editable in your php output, then change your selector for td click handler to
$('tbody').on('click','td.ditable',function() {
As for updating database...need to determine if the ajax request from $.getJSON is being made. You can inspect this within browser console network tab. Also look for errors in console. Request ( if made) will show status, what is sent, what is returned etc
Need to use that as start point to help determine if preoblem lies in server code ( would get a 500 status) or in browser code.
If you provide live html sample ( not php ) from browser source view can create test demos to see what your javascript code is doing . Putting the html and javascript into jsfiddle.net and saving creates a demo that anyone can test out
Related
I have created a page for updation of record. I want to pass the id of student from one page to another. I am trying to send it through window.location but it is not working. In ajax I tried to navigate to other page but didn't succeed in that too. How can i pass the data and receive on other page without showing in query string?
ajax code is
var id = $(this).data('username');
$.ajax({
var id = $(this).data('username');
$.ajax({type: "POST",
cache: false,
data: id,
url: "Update.php",
success: function(dto)
{
//but I do not require this return call I just
// want to pass the data to update.php
}
});
//this is the code where the button is being clicked
<table class="table table-condensed" >
<thead style="background-color:#665851" align="center">
`<tr>
<td style="color:white">Roll No</td>
<td style="color:white">Name</td>
<td style="color:white">Department</td>
<td style="color:white">Click To Update</td>
</tr>
</thead>
<tbody style="background-color:whitesmoke; border:initial" id="tblBody" align="center">
<?php
$database="firstdatabase"; //database name
$con = mysqli_connect("localhost","root" ,"");//for wamp 3rd field is balnk
if (!$con)
{ die('Could not connect: ' . mysql_error());
}
mysqli_select_db($con,$database );
$state = "SELECT rollno ,name, dept FROM student ;";
$result = mysqli_query($con,$state);
$output = 1;
$outputDisplay = "";
$noRows = mysqli_affected_rows($result);
if($result)
{
$num = mysqli_affected_rows($con);
//$row = mysqli_fetch_array($result,MYSQLI_NUM);
while ($row = mysqli_fetch_array($result))
{
$r = $row['rollno'];
$n = $row['name'];
$d = $row['dept'];
$outputDisplay .= "<tr><td>".$r."</td><td>".$n."</td><td>".$d."</td><td align='right'>
<button type='button' name='theButton' value='Detail' class='btn' id='theButton' data-username='$r'> <img src='edit.jpg'/></button>
</td>
</tr>";
}
}
else
{
$outputDisplay .= "<br /><font color =red> MYSql Error No: ".mysqli_errno();
$outputDisplay .= "<br /> My SQl Error: ".mysqli_error();
}
?>
<?php
print $outputDisplay;
?>
</tbody>
</table>
If both pages are at same domain you can use localStorage, storage event to pass data between html documents
At second page
window.addEventListener("storage", function(e) {
// do stuff at `storage` event
var id = localStorage.getItem("id");
});
at first page
// do stuff, set `localStorage.id`
localStorage.setItem("id", "abc");
When you use window.location then your page go to another page. ajax work on active page. You can not use.
Generally you can use sessions for this $_SESSION variable to store it into the session, or you can pass that value via get parameter. And afterwards get that parameter with $_GET
Or $_POST parameter if you want to submit form.
you can try using cookies
Set the cookie
<?php
setcookie("name","value",time()+$int);
/*name is your cookie's name
value is cookie's value
$int is time of cookie expires*/
?>
Get the coockie
<?php
echo $_COOKIE["your cookie name"];
?>
Populate a <form method="post" [...]> in the first page with the information needed; you can change their aspect with CSS as desired.
When the <form> is send you only need a PHP script/page that uses $_POST to fill the new page.
Easier than AJAX if you try to navigate from the first page to the second.
If you already have a form and wanna post that to an update script, you could just add the student id as an hidden form element example:
<input type="hidden" name="student_id" value="<?php echo $student_id; ?>">
Else if you want to redirect from another page to the update page, with a student id, the best way will probably be a $_GET variable.
So the URL would look something like this: http://domain.com/update.php?student_id=1
And then your update.php will include a simple check like this.
if(!empty($_GET['student_id'])) {
$student_id = $_GET['student_id'];
// Ready to update
} else {
// Throw 404 error, or redirect to an create page
}
Hi guys so i have created a simple comment box for my site now. It works perfectly, however the problem i am having is that i have different pages which are going to require different comment box. I cant seem to figure out how to get the comment box to be unique for every page. So right now my database holds this :
Called comments:
id
comment
comment1
comment_date
Now my idea is that everything was stored into comment, so i added comment1 for other page to store the info. However i have no clue how to edit the php file to get it to work with comment1. Any help on this would be great.
HTML:
<div class="comment_container">
<div class="comments">
<?php
include_once("comments.php");
?>
</div>
<div class="comments_form">
<table>
<tr><td><textarea id="comment_text"></textarea></td>
<td><input type="button" id="comment_process" value="Post Comment"/></td></tr>
</table>
</div>
</div>
JS:
$(document).ready(function() {
$('#comment_process').click(function() {
if ($('#comment_text').val() != "") {
$.post("comments.php?action=post", {
comment: $('#comment_text').val()
}, function(data) {
$('.comments').html(data);
$('#comment_text').val("");
});
}
});
});
PHP:
include_once("connect.php");
function convert ($date) {
$converteddate = date("F j, Y g:ia", strtotime($date." +1day"));
return $converteddate;
}
function getComments(){
$comments = "";
$sql = mysql_query("SELECT * FROM comments") or die(mysql_error());
if(mysql_num_rows($sql) == 0){
$comments = "<div class='each_comment'>There are no comments</div>";
} else {
while($row = mysql_fetch_assoc($sql)){
$comments .= "<div class='each_comment'><small><em>".convert($row['comment_date'])."</em></small><br />".$row['comment']."</div>";
}
}
return $comments;
}
function postComments($comment){
$comment = mysql_real_escape_string(strip_tags($comment));
$sql = mysql_query("INSERT INTO comments (comment, comment_date ) VALUES ('".$comment."', now())");
return true;
}
if((isset($_GET['action'])) && ($_GET['action']== "post")){
postComments($_POST['comment']);
}
echo getComments();
Thanks again for the help
DISCLAIMER
For future visitors:
Don't copy this code, as it has several issues that go beyond answering the question.
What you need to add is an identifyer for the type of comment. (Type could be replaced with something more suitable to your case like 'product', 'user', ... whatever the difference is/what they are related to)
So in your database add that new column:
comments
--------
id
comment
type
comment_date
Now you need to pass around that type through all your calls, and it shall be specified in your 'HTML'-Page (which actually is php...).
<div class="comment_container">
<div class="comments">
<?php
// specify the type needed on that page
$type = 1;
include_once("comments.php");
echo getComments($type);
?>
</div>
<div class="comments_form">
<table>
<tr><td><textarea id="comment_text"></textarea></td>
<td><input type="button" id="comment_process" value="Post Comment"/></td></tr>
</table>
</div>
</div>
<script>
// specify the type in javascript
var type=1;
$(document).ready(function() {
$('#comment_process').click(function() {
if ($('#comment_text').val() != "") {
// add the type here:
$.post("comments.php", {
comment: $('#comment_text').val(),
type: type,
action: 'post'
}, function(data) {
$('.comments').html(data);
$('#comment_text').val("");
});
}
});
});
</script>
and in comments.php:
//....some code left out here
function getComments($type){
$comments = "";
$sql = mysql_query("SELECT * FROM comments where type=$type") or die(mysql_error());
if(mysql_num_rows($sql) == 0){
$comments = "<div class='each_comment'>There are no comments</div>";
} else {
while($row = mysql_fetch_assoc($sql)){
$comments .= "<div class='each_comment'><small><em>".convert($row['comment_date'])."</em></small><br />".$row['comment']."</div>";
}
}
return $comments;
}
function postComments($comment, $type){
$comment = mysql_real_escape_string(strip_tags($comment));
$sql = mysql_query("INSERT INTO comments (comment, comment_date, type ) VALUES ('".$comment."', now(), ".$type.")");
return true;
}
if((isset($_POST['action'])) && ($_POST['action']== "post")){
postComments($_POST['comment'], $_POST['type']);
// send all the comments back to client
echo getComments($_POST['type']);
}
// moved to html-file: echo getComments($type);
NOTE
There are several issues with that code.
First don't use mysql functions. For real. Unsecure and deprecated/deleted as of php7. Use mysqli or pdo. Furthermore your sql can be hacked with sql injection. Read about prepared statements.
The general structure of that code is not very good.
Try to seperate output and formating from getting data.
For example it would be much better if a function called 'getComments' only would get the comments from the database, then let others decide what to do with that data. The less one function does the better.
Please read about coding styles, maybe start learning object oriented programming.
I hope this still helps you to get a clue of where to go!
Hi Guys I am stuck with my coding. I hope someone can help me with my problem
So I have this class (updateProgress.php) that pulls the value from the DB and process it thru ajax on the other page called data2.php and display the query when user press the show button to the in (updateProgress.php).
What i have in the data2.php is,
<?php
// IF SHOW KEY HAS BEEN PRESSED
if($_POST['action'] == 'show')
{
$sql = "SELECT * FROM SUB_MASTER_DRAWING
WHERE SUB_MASTER_DRAWING.HEAD_MARK = '{$_POST["hm"]}'";
$query = oci_parse($conn, $sql);
$query_exec = oci_execute($query);
echo "<table border='1'>";
while($row = oci_fetch_assoc($query)){
echo '<div id="content">';
echo '<table cellspacing = "0"';
echo '<tr><th>Head Mark</th>
<th>Cutting</th>
<th>Assembly</th>
<th>Welding</th>
<th>Drilling</th>
<th>Finishing</th>
</tr>';
echo "<tr><td><b>$row[HEAD_MARK]/$row[ID]</b></td>";
if ($row['CUTTING'] == 'Y'){
echo "<td><input type='checkbox' id='cuttingCheckbox' name='cuttingCheckbox' checked='checked' disabled='disabled'/></td>";
} else {
echo "<td><input type='checkbox' id='cuttingCheckbox' name='cuttingCheckbox' onClick='checkboxCheck()' /></td>";
}
?>
So my problem is when user check the checkbox, it should make a query to the database and update the corresponding value. I tried making the javascript function just to check if the checkbox action works on the outside the php tag but it just doesnt do anything.
is it because i pass all the table query to the so that it wont process the javascript ?
please help me
You already have checkbox with onClick='checkboxCheck()' assigned. Just make an ajax call from that javascript function and update whatever value you want from that call. You can create another php file to handle this ajax call.
function checkboxCheck() {
var checkbox1 = document.getElementById("cuttingCheckbox");
if (checkbox1.checked) {
alert('CHECKBOX CHECKED');
} else {
alert('CHECKBOX NOT CHECKED');
}
// Make Ajax call here, to call a php file
// which will update the db table
// You will have to pass other relevant variables like row id etc
}
That code is ready for a SQL Injection.
I'd suggest just using jQuery for handling the clicking of the checkbox:
$('#cuttingCheckbox').click(function() { /* function goes here */ });
(or use mousedown instead of click)
And then just have a simple AJAX call to a PHP file. AJAX is really simple and quick with jQuery.
To me that looks correct, but i'm not experienced with AJAX in the slightest, been stuck at it for hours trying many variations including filter and it's all been useless. This is currently what i have and i can't see anything wrong with it.
What is happening is that no chat messages are showing up like they usually do, if i was to just refresh the page.
What i am simply trying to accomplish is a chat interface if that has any relevance.
Here is a live example of what is happening: http://www.mixpix.eu/chat/chat.php?r=G97NxXy4exbLQPFU
$(document).ready(function() {
var interval = setInterval(function() {
$.ajax({
dataType: "html",
url: 'chat.php?r=' + <?php echo "'" .$_GET['r']. "'"; ?> ,
success: function(data) {
var trim = $(data).find('.message_window');
$('.message_window').replaceWith(trim);
}
});
}, 1000);
});
Here's the contents of my body tag:
<div class="wrapper">
<div class"inbox_window" id="style-3">
</div>
<div class="message_window" id="style-3">
<table width="100%">
<p class="talking_to"><?php echo getFirstnamebyID($_GET['r']); ?></p>
<?php echo displayMessages(); ?>
</table>
</div>
<form class="submit_form" method="post" <?php echo 'action="chat.php?r='.$_GET['r'].'"' ?>>
<input type="text" name="message" placeholder="Type message here" />
<input type="submit" value="Send" name="s_say"/>
</form>
</div>
displayMessages() function in php:
function displayMessages() {
$user_id = getUserID();
$sql = mysql_query(strip_tags("SELECT * FROM inbox WHERE (send_id='".$user_id."' OR send_id='".$_GET['r']."') AND (rec_id='".$_GET['r']."' OR rec_id='".$user_id."') ORDER BY timestamp;"));
if (mysql_num_rows($sql) != 0) {
while($row = mysql_fetch_assoc($sql)) {
if ($row['send_id'] == $user_id) {
echo '<tr><td><p class="sm">'. $row['messages'] .'</p></td></tr>';
} else if ($row['send_id'] == $_GET['r']) {
echo '<tr><td><p class="rm">'. $row['messages'] .'</p></td></tr>';
} else {
echo "Unable to display messages.";
}
}
} else {
echo "Be the first to say hello!";
}
}
I would be highly thankful for any ones help as it's driving me a bit insane.
You've got a few things happening here that are going to cause you problems...
On the JavaScript side, setInterval is a hacky way to keep your content current, this could better be achieved with sockets. If you really want to do it this way, returning the whole document (including the HTML head) is not your best option -- maybe send an extra query param that tells your PHP to only send the messages section, or better yet, the messages that have been added since the timestamp you last checked.
In your markup, you can't put a paragraph tag directly inside your table, or raw text, as can come back from your PHP. You're not really using it as a table anyway, a list would probably be more semantic.
Background: I am using HTML/PHP/MySQL/ and Javascript if needed
What I have is a list of approximately 1000 people - I want to let the user select people, and then use the selected people to add them to a database.
I was thinking that each row of the table would have a unique link, and the link would either add that person to an array - or to some kind of list - and then at the end I can take that list and input it into the database..
I really want to have it that when somebody clicks a person's name - it automatically gets added to a list on lets say the left hand side - then once they are done, they can submit the list.
let me know if clarification is needed.
Thanks for your help!
I would go with:
Create page with space for smaller list on the left and list of people on the right.
Display people, with pagination, in table using something like this:
<table id="people">
<tr>
<td id="<?php echo $person['id']; ?>"><?php echo $person['name']; ?></td>
</tr>
</table>
When someone clicks on tr javascript code is executed to send post request with id the person. PHP file responsible for handling this stores the id in the $_SESSION['selectedPeople'] array or removes it from there if it is present. Also, when you click on td, .selected class is toggled and list of selected people on the left side is updated(for example, via getting JSON from PHP file and processing it to display in the table).
you can press submit at any time. It would:
a) take you to the other page and submit the list(you have $_SESSION['selectedPeople'] variable)
b) send an ajax call to page which will process $_SESSION['selectedPeople']
Some code:
selectHandler.php:
<?php
if($_POST && isset($_POST['id'])) {
$id = (int)$_POST['id'];
$action = '';
session_start();
if(!isset($_SESSION['selectedPeople'])) {
$_SESSION['selectedPeople'] = array($id);
$action = 'added';
} else {
if(in_array($id, $_SESSION['selectedPeople'])) {
$_SESSION['selectedPeople'] = array_diff($my_array, array($id));
$action = 'removed';
} else {
$_SESSION['selectedPeople'][] = $id;
$action = 'added';
}
}
echo json_encode(array('action' => $action));
}
?>
Javascript(+JQuery):
$(function () {
$('#people tr').click(function () {
var id = $(this).children('td[id]').attr('id');
$.post("selectHandler.php", { id: id })
.done(function( data ) {
if(data.action == "added") {
$(this).addClass('selected');
} else if(data.action == "removed") {
$(this).removeClass('selected');
} else {
alert('Some kind of error.');
}
}, "json");
refreshSelectedList();
});
});
I hope you get the idea.