save values from html table to database - php

i have a html table that displays values from the database. I have a javascript that enables me to edit this data but then i cant figure out how to save it back to the database using php. i found some information that i should use xmlhttprequests but i have no idea on how to do this. Any suggestions? Your help is highly appreciated. Code below;
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script type="text/javascript"><!--
function edit_input(obj) {
var is_checked = obj.checked;
while (obj.tagName!='TR')
obj = obj.parentNode;
var td = obj.getElementsByTagName('TD');
var len = td.length;
if (!is_checked) {
for (var i=0; i<len; i++)
if (td[i].className=='editable')
td[i].innerHTML = td[i].firstChild.value;
} else {
var input;
for (var i=0; i<len; i++)
if (td[i].className=='editable') {
input = document.createElement('INPUT');
input.value = td[i].innerHTML;
td[i].innerHTML = '';
td[i].appendChild(input);
}
}
}
--></script>
</head>
<body>
<table border="1">
<tr>
<th width="56">Branch ID</th>
<th width="75">Branch Name</th>
<th width="75">Branch Personnel</th>
<th width="105">Branch Headquaters</th>
<th width="50">Edit</th>
</tr>
<?php
$result = mysql_query($query );
while ($row= mysql_fetch_array($result)) { ?>
<tr>
<td class="editable"><?php echo $row['branchid'];?></td>
<td class="editable"><?php echo $row['branchname'];?></td>
<td class="editable"><?php echo $row['branchpersonnel'];?></td>
<td class="editable"><?php echo $row['branchhq'];?></td>
<td><input type="checkbox" onclick="edit_inpu(this);">Edit</td>
</tr>
<?php } ?>
<tr><td><input type="submit" name="editbranch" class="button2" value="Update"/></td></tr>
</table>
</body>
</html>

If using jQuery is not a problem, maybe using something like JEditable is a solution. When you click on a cell in a table, it turns into a textfield, and when pressing enter or leaving focus, it makes a webrequest to the server, where you can make the changes.
See for example this jsfiddle script. It's really easy to use. The only other thing you would need to do is to give the table cells an id, which gets sent to the page you are saving it too.

Have your script fire off an Ajax request through XMLHttpRequest to a PHP script that saves the values back to the database.
The URL could be something like this: updatetable.php?row=0&col=0&data=1234

You could use jquery, is very popular.
you have to download the lib and include-it on the header
http://code.jquery.com/jquery-1.7.min.js
and here it's how you use a ajax request with jquery:
http://api.jquery.com/jQuery.ajax/
The url param is your location to send the values to save them like the post.

Related

How do I stop duplication in <p> tag? I am trying to load data from my JSON file and display in the website with .html() function

Here is a screen shot of the problem
The original file has some hard coded data and I am suppose to replace this data with the one I have in my JSON file, I tried that with this code, made some progress but every time I click on the other e mail header the same data gets placed in the tag of my html file (index). I need to find a way to stop data from duplicating. Can somebody help me?! I am new in AJAX/JSON
$(document).ready(function() {
$.getJSON("email_list.js",
{format: "json"}).done(function(data){
console.log(data);
for (key in data) {
emailID = "#" + data[key].id;
$(".email-header")
.eq(key).attr("id", data[key].id);
$(emailID).find('td')
.eq(0).attr("id", "sender" + data[key].id)
.html(data[key].sender);
$(emailID).find('td')
.eq(1).attr("id", "subject" + data[key].subject)
.html(data[key].subject);
$(emailID).find('td')
.eq(2).attr("id", "datetime" + data[key].datetime)
.html(data[key].datetime);
}
});
// show/hide emails when click on headers
$("tr.email-header").click(function(){
id = "#body " + $(this).attr("id");
//creates the name for each file
fileID = $(this).attr("id") + ".js";
//console.log(id);
$.ajax({
url: fileID,
dataType: "JSON",
success: function(data) {
console.log(data);
//I need to replace the contents in the HTML file with
//my JASON file contents.
fElement = $("tr.email-body").find("p");
fElement.eq(0).html(data.recipient);
fElement.eq(1).html(data.body);
fElement.eq(2).html(data.recipient);
fElement.eq(3).html(data.body);
fElement.eq(4).html(data.recipient);
fElement.eq(5).html(data.body);
}}).fail(function() {
console.log(id + " - HAS AN ERROR!");
});
$(this).next().eq(0).toggle();
});
// hide email on click
$("tr.email-body").click(function(){
$(this).hide();
});
});
Here's an updated snippet that is pulling ajax data from your github repo. Just trace through to see how we are accessing the elements in the js file.
Some additional notes:
Try to use classes for repetitive elements like sender subject and datetime rather than ids. Then it is even easier to access them. I didn't change that.
You have it set to reload the email every time it's header is clicked. Might want to ensure to only load once.
You should clear out the existing html right away so the placeholder text isn't shown for a split second before the real content gets loaded.
$(document).ready(function() {
$.getJSON("https://raw.githubusercontent.com/checonunez74/AJAX-JSONproject/master/email_list.js", {
format: "JSON"
}).done(function(data) {
for (key in data) {
emailID = "#" + data[key].id;
$(".email-header")
.eq(key).attr("id", data[key].id);
f_el = $(emailID).find('td');
f_el.eq(0).attr("id", "sender")
.html(data[key].sender);
f_el.eq(1).attr("id", "subject")
.html(data[key].subject);
f_el.eq(2).attr("id", "datetime")
.html(data[key].datetime);
}
});
// show/hide emails when click on headers
$("tr.email-header").click(function() {
let id = $(this).attr("id"),
emailBody = $(this).next(".email-body"),
emailRecipient = emailBody.find('p').first(),
emailContent = emailBody.find('p').last();
//make the AJAX call here
$.ajax({
url: 'https://raw.githubusercontent.com/checonunez74/AJAX-JSONproject/master/' + id + '.js',
dataType: "JSON",
success: function(data) {
emailRecipient.text('To: ' + data.recipient);
emailContent.text(data.body);
}
}).fail(function() {
console.log(id + " - HAS AN ERROR!");
});
emailBody.toggle();
});
// hide email on click
$("tr.email-body").click(function() {
$(this).hide();
});
});
.email-body {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<!-- Latest compiled and minified JavaScript -->
<script src="http://code.jquery.com/jquery.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<script src="email.js"></script>
<link rel="stylesheet" href="email.css">
</head>
<body>
<h1>Email Inbox</h1>
<table class="table table-hover" id="inbox">
<thead>
<tr class="active">
<th>Sender</th>
<th>Subject</th>
<th>Received</th>
</tr>
</thead>
<tbody>
<tr class="warning email-header">
<td>Bob</td>
<td>Re: Your brains</td>
<td>01/03/2014 9:56pm</td>
</tr>
<tr class="email-body">
<td colspan="3">
<p>To: Tom#tom.tom</p>
<p>Heya Tom, it's Bob, from the office down the hall...</p>
</td>
</tr>
<tr class="warning email-header">
<td>Your only friend</td>
<td>I've been shockingly nice</td>
<td>04/07/2011 12:34pm</td>
</tr>
<tr class="email-body">
<td colspan="3">
<p>To: want#you.gone</p>
<p>That's what I'm counting on.</p>
</td>
</tr>
<tr class="warning email-header">
<td>Mr. Fancy Pants</td>
<td>Chances are...</td>
<td>10/21/2005 4:16am</td>
</tr>
<tr class="email-body">
<td colspan="3">
<p>To: dancing#the.parade</p>
<p>You thought you had some fancy pants and now you know it's true.</p>
</td>
</tr>
</tbody>
</table>
</body>
</html>

Edit particular field in a row of the table and update edited value in MySQL table

I am fetching data from database in a table.Now i want to edit particular field in a row of the table and save that value into MySQL.
This is my complete code for displaying data in table and editing. Here i want to edit the status. It is editable but after editing how to get the value from the table and update that value to MySQL.
<?php
include "config.php";
$sql = "select * from d_jobs where Status ='drafted' ";
$result = mysqli_query($conn,$sql);
$count = mysqli_num_rows($result);
//echo $count;
?>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script>
$("document").ready(function(){
$('#sdata').click(function(){
var myTxt = $(('.status')+[i]).html();
console.log(myTxt);
var id = $(('.status')+[i]).attr('id');
console.log(id);
}
/* $.ajax({
type: 'post',
url: 'job_field_edit.php',
data: 'varname=' +myTxt
}); */
});
});
</script>
</head>
<body>
<table border="2" align="center">
<thead>
<tr>
<th>Job Name</th>
<th>Builder</th>
<th>Job Type</th>
<th>Status</th>
<th>Effective Date Start</th>
<th>Estimated completion date</th>
<th>Job Gal Glag</th>
<th>Take List Flag</th>
<th>Planner</th>
<th>Project Manager</th>
<th>Hand Over</th>
<th>Other Comments</th>
</tr>
</thead>
<tbody>
<?php
if( $count ==0 ){
echo '<tr><td colspan="4">No Rows Returned</td></tr>';
}else{
while( $row = mysqli_fetch_array($result)){
echo "<tr><td>{$row['JOB_NAME']}</td>
<td>{$row['BUILDER']}</td>
<td>{$row['JOB_TYPE']}</td>
<td contenteditable='true' id='{$row['JOB_ID']}' class='status[{$row['JOB_ID']}]'>{$row['status']}</td>
<td>{$row['EFFECTIVE_START_DATE']}</td>
<td>{$row['ESTIMATED_COMPLETION_DATE']}</td>
<td>{$row['JOB_GAL_FLAG']}</td>
<td>{$row['JOB_TAKE_LIST_FLAG']}</td>
<td>{$row['Planner']}</td>
<td>{$row['Project_Manager']}</td>
<td>{$row['Handover']}</td>
<td>{$row['Comments']}</td>
<td><input name='need_delete[{$row['JOB_ID']}]' type='checkbox' id='checkbox[{$row['JOB_ID']}]' value='{$row['JOB_ID']}'></td>
</tr>\n";
}
}
?>
</tbody>
</table>
<input id="sdata" type="button" value="Send Data" />
</body>
</html>
<?php
mysqli_close($conn);
?>
There's a number of ways to approach this. One is to dispense with the manual Send Data button and allow javascript to respond automatically to users' contenteditable edits.
Unfortunately, contenteditable elements don't fire a change event but they do fire a blur event, from which a change event can be triggered.
First, build your contenteditable elements like this :
<td contenteditable=\"true\" class=\"status\" data-job-id=\"{$row['JOB_ID']}\">{$row['status']}</td>
Then, for each contenteditable element, attach a blur handler, and initialize a data-value attribute equal to innerText.
$('[contenteditable]').on('blur', function(e) {
var self = $(this);
if(self.text() !== self.data('value')) {
self.trigger('change');
}
self.data('value', self.text());
}).each(function() {
$(this).data('value', $(this).text()); // equivaluent to data-value="{$row['status']}".
});
Thus you can have contenteditable elements that mimic, at least in part, HTML input elements.
So now you can attach a change handler as you would for a standard HTML input element.
$(".status").on('change', function(e) {
var job_id = $(this).data('jobId');
var old value = $(this).data('value');
var current value = $(this).text(); // in this regard, <input> is not mimicked. For a genuine <input> we would write `$(this).val()`.
// here, perform ajax to keep server-side up to date.
});
DEMO
Note: This approach is slightly over-the-top when [contenteditable] and .status are virtual synonyms for each other. However, in the general case where there might be several different classes of contenteditable element, then you would likely avoid much repetition of code.

Ajax with php classes

I want to use AJAX to show a form when a user clicks on record to edit it.
I know and capable of using AJAX.
But now i want to call a method of a class in PHP. And thats where im stuck.
Below some code sample of my controller:
public function start() {
$users = $this->usersmodel->getAllUsers();
$firstRow = new HtmlTableFirstRow();
$table = new HtmlTable($users,$users,$firstRow);
$table->setCss('table1');
echo $table->show();
}
public function editRecord() {
$recordId = $this->getFirstParameter();
$user = $this->usersmodel->getUserById($recordId);
$tableId = $this->fieldModel->getTableIdByName('users');
$inputs = $this->fieldModel->getFields($tableId);
$collection = new Fieldcollection($inputs);
foreach($collection as $inputs) {
for($i = 0; $i < count($inputs); $i++) {
foreach($user as $userInfo) {
$inputs[$i]->setValue($userInfo[$i]);
}
}
}
$form = new Form($collection);
$form->setLabels();
$form->setCss('form1');
echo $form->show();
}
As you can see i have 2 functions, start which shows all the records. And when a user clicks on editrecord a form will show.
I want to show the form in a popup, without a page refresh.
What is the best way to handle this?
You can make a page for manage ajax requests like this:
server.php :
if(isset($_GET['request'])){
switch($_GET['request']){
case 'get-form' :
$userId = $_GET['userId'];
$form = new Form($collection);
$form->setLabels();
$form->setCss('form1');
echo $form->show();
break;
}
}
in client page you can send ajax request & get their result via jquery :
client.html :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<table>
<tr data-userId="1">
<td>User 1</td>
<td><button class="edit">Edit Record</button></td>
</tr>
<tr data-userId="2">
<td>User 2</td>
<td><button class="edit">Edit Record</button></td>
</tr>
<tr data-userId="3">
<td>User 3</td>
<td><button class="edit">Edit Record</button></td>
</tr>
</table>
<div class="popup">
</div>
</body>
<script src="jquery.js"></script>
<script src="ajax.js"></script>
</html>
ajax.js :
(function(){
$('.popup').hide();
$('.edit').on('click',function(){
var userId = $(this).parent().parent().data('userId');
$.get('server.php',{request : 'get-form' , userId : userId},function(form){
$('.popup').empty().append(form).fadeIn();
});
});
})();
I hope this helps you

On hover show image from data attribute from google image search

I am trying to incorporate a code that will allow me to assign a class to a table that is "hoverme" then once a user hovers over that cell, it then does an ajax query to using the data-attribute with the information stored in there to a google search.
here is a mock up table:
<table>
<thead>
<tr><td>Test</td><td>Name</td></tr>
</thead>
<tbody>
<tr><td data-info="Samsung NP200A5B" class="hoverme">ABC123</td><td>Test Name</td> </tr>
</tbody>
</table>
Once a user hovers over the name abc123 it should show a pic above it of what is in the data-info tag.
I am not sure of how the jquery is going to work nor do i know if this is even going to work because everything is generated from a MySQL database.
here is my php code:
<?php
$qry = "SELECT * FROM `assets` WHERE cust_id='$custID'";
$rs = mysqli_query($mysqli,$qry) or die("Error: ".mysqli_error($mysqli));
if(mysqli_num_rows($rs) > 0)
while($rowa = mysqli_fetch_array($rs)) {
echo '
<tr>
<td>'.$rowa['asset_tag'].'</td>
<td>'.ucwords ($rowa['type']).'</td>
<td>'.ucwords ($rowa['vendor']).'</td>
<td>'.ucwords ($rowa['model']).'</td>
<td>'.ucwords ($rowa['platform']).'</td>
<td>'.ucwords ($rowa['location']).'</td>
<td>'.ucwords ($rowa['status']).'</td>
<td>'.ucwords ($rowa['user']).'</td>
<td><a data-toggle="modal" href="#myModal" id="'.$rowa['id'].'">View</a></td>
<td>Edit</td>
<td>'?> <?php if($rowa['del_flag'] == 0){ echo' Delete'; }else{ echo 'Undo Delete'; }?> <?php echo '</td>
<td><span class="glyphicon glyphicon-qrcode"></span></td>
</tr>'.PHP_EOL;
}else
echo "
<tr>
<td>No assets found</td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr> ".PHP_EOL;
?>
One last thing i should mention is i am using Jquery's DataTable.
This can be through the Google Image Search API, but with the daily usage limit (or pay $5 per 100 search).
See: https://developers.google.com/image-search/
Even using this API, you cannot ensure that the every searched image matches as the one you expecting to show in your page.
Sample API:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google Search API Sample</title>
<script src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('search', '1');
var imageSearch;
function addPaginationLinks() {
// To paginate search results, use the cursor function.
var cursor = imageSearch.cursor;
var curPage = cursor.currentPageIndex; // check what page the app is on
var pagesDiv = document.createElement('div');
for (var i = 0; i < cursor.pages.length; i++) {
var page = cursor.pages[i];
if (curPage == i) {
// If we are on the current page, then don't make a link.
var label = document.createTextNode(' ' + page.label + ' ');
pagesDiv.appendChild(label);
} else {
// Create links to other pages using gotoPage() on the searcher.
var link = document.createElement('a');
link.href="/image-search/v1/javascript:imageSearch.gotoPage("+i+');';
link.innerHTML = page.label;
link.style.marginRight = '2px';
pagesDiv.appendChild(link);
}
}
var contentDiv = document.getElementById('content');
contentDiv.appendChild(pagesDiv);
}
function searchComplete() {
// Check that we got results
if (imageSearch.results && imageSearch.results.length > 0) {
// Grab our content div, clear it.
var contentDiv = document.getElementById('content');
contentDiv.innerHTML = '';
// Loop through our results, printing them to the page.
var results = imageSearch.results;
for (var i = 0; i < results.length; i++) {
// For each result write it's title and image to the screen
var result = results[i];
var imgContainer = document.createElement('div');
var title = document.createElement('div');
// We use titleNoFormatting so that no HTML tags are left in the
// title
title.innerHTML = result.titleNoFormatting;
var newImg = document.createElement('img');
// There is also a result.url property which has the escaped version
newImg.src="/image-search/v1/result.tbUrl;"
imgContainer.appendChild(title);
imgContainer.appendChild(newImg);
// Put our title + image in the content
contentDiv.appendChild(imgContainer);
}
// Now add links to additional pages of search results.
addPaginationLinks(imageSearch);
}
}
function OnLoad() {
// Create an Image Search instance.
imageSearch = new google.search.ImageSearch();
// Set searchComplete as the callback function when a search is
// complete. The imageSearch object will have results in it.
imageSearch.setSearchCompleteCallback(this, searchComplete, null);
// Find me a beautiful car.
imageSearch.execute("Subaru STI");
// Include the required Google branding
google.search.Search.getBranding('branding');
}
google.setOnLoadCallback(OnLoad);
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
<div id="branding" style="float: left;"></div><br />
<div id="content">Loading...</div>
</body>
</html>

How to refresh contents of div after link is clicked

I have a form which contains a dropdown box, when the value is changed the form uses jQuery and ajax to produce a table. The table contains data based on the value of the dropdown box and also links.
My initial script which is where the dropdown box is and where the table is added is:
<?php require_once('/connections/db.php');
mysql_select_db($database_db, $db);
$query_weeks = "SELECT WeekNo, WeekName FROM tbl_weeks ORDER BY WeekNo ASC";
$weeks = mysql_query($query_weeks, $db) or die(mysql_error());
$row_weeks = mysql_fetch_assoc($weeks);
$totalRows_weeks = mysql_num_rows($weeks);
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<form name="form1" method="post" action="">
<select id="weekselect" name="week">
<?php
do {
?>
<option value="<?php echo $row_weeks['WeekNo']?>"><?php echo $row_weeks['WeekName']?></option>
<?php
} while ($row_weeks = mysql_fetch_assoc($weeks));
$rows = mysql_num_rows($weeks);
if($rows > 0) {
mysql_data_seek($weeks, 0);
$row_weeks = mysql_fetch_assoc($weeks);
}
?>
</select>
</form>
<div id="mydata"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function (){
// listen to change in monthselect
$('#weekselect').change(function(){
var week= $('#weekselect option:selected').val();
//pass val to php
$.post('test2.php',{week: week}, function(data) {
//do something with the data
$('div#mydata').html(data);
});
});
});
</script>
</body>
</html>
The script produces the dropdown from the mysql db and creates a listener for it, when the select is changed the value of the select is passed to the test2.php using jquery. the data returned is added to div #mydata
Test2 which produces the table is as follows
<?php
if (!isset($_SESSION)) {session_start();}
include('session.php');
require_once('Connections/dbc.php');
$open_week=$_SESSION['MM_OpenWeek'];
$week_selected=$_POST['week'];
$season=$_SESSION['MM_Season'];
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<?php
echo '<p>Week selected: '.$week_selected .'<p>';
echo '<p>Open Week: '.$open_week .'<p>';
if ($week_selected>=$open_week) {
echo '<p>Week Open<p>';
} else {
echo '<p>Week Closed<p>';
}
//create recordset of fixtures for the week selected
$sql="SELECT * FROM q_games_stats WHERE WeekNo =".$week_selected . " and Season=". $season ." and at='Home' ORDER BY WeekNo ASC";
$rec_games=mysqli_query($dbc,$sql);
//create table using the recordset
?>
<div id="data_table">
<table class="table" align="center">
<th class="th" width="80px">Match Date</th>
<th class="th" width="150px">Home Team</th>
<th class="th" width="40px">Score</th>
<th class="th" width="150px">Away Team</th>
<th class="th" width="150px">Link</th>
<?php
while ($row=mysqli_fetch_array($rec_games))
{
?>
<tr class="tr">
<td class="td"><?php echo $row['MatchDate']?></td>
<td class="td"><?php echo $row['TeamName']?></td>
<td class="td"><?php echo $row['Score']?></td>
<td class="td"><?php echo $row['OppName']?></td>
<td class="td">Link</td>
</tr>
<?php
}
?>
</table>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function (){
// listen to change in monthselect
$('#data_table a').click(function(){
alert("link clicked");
});
});
</script>
</body>
</html>
This produces the table, which includes links. There is an event listener of the links in the table, which when I click produces an alert.
What I want to do is instead of an alert being produced when clicking a link is for the table to reproduce, the reason for this is when the user clicks a link it will run a script which will change the underlying data in the table and therefore the table will need to be refreshed.
Is there I way I can do this, or is there a better way to do what I want to do?

Categories