I have a table that works like this: http://www.datatables.net/examples/api/editable.html without the header sorting, page changing, and search. I have another functionality that allows me to add a row. All of this is done on the same page. The data is drawn directly from a database. I wrote the code generic so it could be used for any table I want to display.
However, I have came across a problem. Let's say an end-user wants to see a list of houses. This list would be drawn from a houses database. Each house has an owner. There is also an owners table. Each owner has an id (primary_key). In the houses table the owner field uses the owner's id to identify the proper owner. Here is where the problem arises. Once the data from the houses table is displayed the owner, for instance, shows up as an id number. Obviously, to the end-user it either is meaningless or at least annoying. I would like to have, in this case the owner's name, the field that is in question to show instead of a "seemingly" meaningless field. I'm posting the relevant code for my predicament.
Also, can I change mySQL booleans through jQuery? What I mean by that is if, for example, a house is not up for rent so the for_rent flag is set to 0 for FALSE. The table will show 0, as that is what is in the table. Can I change that through jQuery? (Find the 0s or 1s and make them say true or false? Any suggestions as to a direction for answering these questions would be great. Thanks.
Here is the relevant code:
PHP to display table:
public function displayTable($table)
{
//connect to DB
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
echo "<table id='table' border='1'>"; //start an HTML table
$dbtable = $table;
$fields =array();
$result = mysqli_query($con, "SHOW COLUMNS FROM ".$dbtable);
//fill fields array with fields from table in database
while ($x = mysqli_fetch_assoc($result))
{
$fields[] = $x['Field'];
}
$fieldsnum = count($fields); //number of fields in array
//create table header from dbtable fields
foreach ($fields as $f)
{
echo "<th>".$f."</th>";
}
//create table rows from dbtable rows
$result = mysqli_query($con, "SELECT * FROM ".$dbtable);
while ($row = mysqli_fetch_array($result))
{
$rowid = $row[$fields[0]];
echo "<tr class='edit_tr' id='".$rowid."'>";
foreach ($fields as $f)
{
echo "<td class='edit_td' data-field='".$f."'><span id='".$rowid."' class='text'>".$row[$f]."</span>
<input type='text' value='".$row[$f]."' class='editbox' id='".$rowid."' data-field='".$f."'/> </td>";
}
$rowid++;
echo "</tr>";
}
echo "</table>"; //close the HTML table
$recordid = $rowid;
//close connection
mysqli_close($con);
}
jQuery to live edit table:
$(document).ready(function()
{
$(".edit_td").click(function()
{
$(this).children(".text").hide();
$(this).children(".editbox").show();
}).children('.editbox').change(function()
{
var table = $('body').attr('id');
var id=$(this).closest('tr').attr('id');
var field=$(this).data('field');
var text=$(this).val();
var dataString = {table:table, id:id, field:field, text:text};
if (field != text)
{
$.ajax({
type: "POST",
url: "classes/table_edit_ajax.php",
data: dataString,
cache: false,
success: function(html)
{
window.location.reload(true);
}
});
}
else
{
alert('Enter something.');
}
});
// Edit input box click action
$(".editbox").mouseup(function()
{
return false
});
// Outside click action
$(document).mouseup(function()
{
$(".editbox").hide();
$(".text").show();
});
});
jQuery to live add row:
$(document).ready(function()
{
$(".add").click(function()
{
var fieldArray = [];
var $table = $("#table");
var $lastRow = $table.find("tr:last");
var $dataFields = $lastRow.find("td");
$dataFields.each(function() {
fieldArray.push($(this).attr("data-field"));
});
$("#table").each(function()
{
var $table = $(this);
var id=$('#table tr:last').attr('id');
var $tr = $("#table").children('tr');
var tablename = $('body').attr('id');
var n = $('tr:last td', this).length;
var tds = '<tr class="edit_tr" id="' + id++ + '">';
for(var i = 0; i < n; i++)
{
tds += '<td class="edit_td" data-field="' + fieldArray[i] +
'"><span id="'+ id +'" class="text"> </span><input type="text" class="editbox" id="' +
id + '" data-field="' + fieldArray[i] + '"/> </td>';
console.log('id: ' + id);
}
tds += '</tr>';
var dataString = {table:tablename, id:id};
if($('tbody', this).length > 0)
{
$('tbody', this).append(tds);
$.ajax({
type: "POST",
url: "classes/table_new_ajax.php",
data: dataString,
cache: false,
success: function(html)
{
window.location.reload(true);
}
});
}else {
$(this).append(tds);
}
});
});
});
you will probably want to extend your generic function for generating the html table to include a joined db table if necessary, though that would get messy, so, create a new function for when you need to join 2 db tables.
The sql for retrieving the owners name into the list of houses would go something like (with a guess at what your field names are):
select a.housename,a.street,a.for_rent,b.name from houses a, owners b where a.owner_id=b.id
Related
I have this code in which I am trying to show and hide the data on clicking a product number and the data is being fetched from database through AJAX. I want the data to be shown beneath the desired row. I want to put the data in tbody and show it on clicking its product number.
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
?>
<tr><td align="center"><?php echo $row['FONumber']; ?></td></tr>
<tbody id='sd'<?php echo $p; $p++; ?>></tbody>
<?php }
}
Javascript and AJAX:
$(function(){
$('#hover1').on({
mouseenter:function(){$(this).css("background","grey")},
mouseleave:function(){$(this).css("background","white")}},'tr');
});
// number of tds
var c = $('#hover1').find('td').length;
var id = document.getElementById("hover1");
for(var i = 0; i < c; i++){
id.rows[i].onclick=(function(){
var a = $(this).find('td:eq(0)').text();
$.ajax({
url: 'printpo1.php',
type: 'post',
data: {fo:a},
success: function(data){
$('#name').html(data);
}
});
$('#sd'+i).toggle();
alert('#sd'+i);
});
}
So far the data I am trying to fetch is showing in the tbody of the first row. Any help will be really appreciated.
I am having problems with a list box that is set to multiple.
My setup is 3 individual list boxes, Categories(single select), Jobs(single select), and Tasks(multiple select)
When a users selects one item in Categories an ajax request populates the Jobs list box.
when a user selects one item from Jobs an ajax request populates the tasks box with one or more pre-selected items, plus the un-selected items.
All this works well my problem araises when I try to select additional items in tasks the pre selected items clear. I need the pre selected items to remain selected and be able to select additional items. I am using a function to select the additional item and refresh the tasks list box so that I do not have to press ctrl when selecting an item.
Here is my html
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title></title>
<script type="text/javascript" src="js/jquery-1.11.2.js"></script>
<?php
session_start();
include('dbcon/dbconnect.php');
$con=mysqli_connect($host,$user,$password,$db);
?>
<script>
function getSelectedItems(){
var items = "";
var frm = document.forms[0].s1;
var len = frm.length;
for(i=0;i<len;i++){
if(frm[i].selected){
items += frm[i].value + "~";
}
}
alert(items);
}
$(document).ready(function(){
$("select#cat").change(function(){
var cat_id = $("select#cat option:selected").attr('value');
$("#job").html( "" );
if (cat_id.length > 0 ) {
parent.top.$("#jobbtn").val("Change Category");
$.ajax({
type: "POST",
url: "fetch_jobs.php",
data: "cat_id="+cat_id,
cache: false,
beforeSend: function () {
$('#job').html('<img src="loader.gif" alt="" width="24" height="24">');
},
success: function(html) {
$("#job").html( html );
}
});
}
});
$("select#job").change(function(){
var job_id = $("select#job option:selected").attr('value');
invid = 0;
$("#task").html( "" );
if (job_id.length > 0 ) {
$.ajax({
type: "GET",
url: "1a.php",
data: "job_id="+job_id+"&invid="+invid,
cache: false,
beforeSend: function () {
},
success: function(html) {
$("#task").html( html );
var selected = $("#task").val();
}
});
}
});
});
function getnotes(){
}
</script>
</head>
<body>
<form id="form1" >
<select id="cat" size="12" style='font-style:arial;font-size:14px;'>
<?php
$result = mysqli_query($con, "SELECT CatID, Catagory FROM catagory ORDER BY Catagory");
while($row = mysqli_fetch_array($result))
{
echo "<option value=\"".$row['CatID']."\">".$row['Catagory']."</option>\n ";
}
echo "</select>";
echo "<Div style='position:absolute;left:70px;top:0px;width:25px;z-index:1014;text-align:center;'>";
echo "<span id='jobl' style='position:fixed;left:180px;top:3px;font-family:Arial;font-size:15px;background-color:#FF9933 ;width:340px;height:20px;'>Jobs</span></div>";
echo "<select name='job' id='job' size='12' style='position:fixed;left:180px;top:23px;width:340px;font-size:14px;font-family:Arial;' onchange='' >";
echo "<option value='' ></option>";
echo "</select>";
echo "<Div style='position:absolute;left:70px;top:px;width:25px;z-index:1014;text-align:center;'>";
echo "<span id='taskl' style='position:fixed;left:535px;top:3px;font-family:Arial;font-size:15px;background-color:#FF9933;width:335px;height:20px;'>Tasks</span></div>";
echo "<select name='task' id='task' size='12' style='position:fixed;left:535px;top:23px;width:335px;font-size:14px;font-family:Arial;' onchange='getnotes()' multiple>";
echo "<option value='' ></option>";
echo "</select>";
echo "<input type='submit' id='taskb' name='taskb' style='position:fixed;top:330px;left:700px;width:150px;height:60px;font-size: 22px;font-weight: bold;white-space:normal;background:Lime;' value= 'Add Task->' onclick='shofinal();'></form></div>";
echo "</form>";
?>
<script>
(function() {
var selected = {};
$('select#task').click(function(e) {
var $this = $(this),
options = this.options,
option,
value,
n;
// Find out what option was just added
value = $this.val();
// Re-apply the selections
for (n = 0; n < options.length; ++n) {
option = options[n];
if (option.value == value) {
// The one being updated
selected[value] = !selected[value];
}
// One of the others
option.selected = !!selected[option.value];
}
});
})();
</script>
</body>
</html>
I believe my problem is in the script at the end of the html but I am unsure of what to change to fix this.
I have finally gotten this worked out thought I would post what fixed it for others to see/use
I added this jquery to the $(document).ready(function()
and now pre selected items stay selected and newly selected items are selected or if I click an item that is already selected it becomes unselected. I am pretty sure I understand what is happening here though I can not put it into words. But it works and I guess that is whats important.
I also removed the script from the end of the original html and everything is good so far.
Works in FF
window.onmousedown = function (e) {
var el = e.target;
if (el.tagName.toLowerCase() == 'option' && el.parentNode.hasAttribute('multiple')) {
e.preventDefault();
// toggle selection
if (el.hasAttribute('selected')) el.removeAttribute('selected');
else el.setAttribute('selected', '');
// hack to correct buggy behavior
var select = el.parentNode.cloneNode(true);
el.parentNode.parentNode.replaceChild(select, el.parentNode);
}
}
I have this section of code that is suppose to get the Values of the input fields and then add them to the database. The collection of the values works correctly and the insert into the database works correctly, I am having issue with the data posting. I have narrowed it down to the data: and $__POST area and im not sure what I have done wrong.
JS Script
$("#save_groups").click( function() {
var ids = [];
$.each($('input'), function() {
var id = $(this).attr('value');
//Put ID in array.
ids.push(id);
console.log('IDs'+ids);
});
$.ajax({
type: "POST",
url: "inc/insert.php",
data: {grouparray: ids },
success: function() {
$("#saved").fadeOut('slow');
console.log('Success on ' + ids);
}
});
});
PHP Section
<?php
include ('connect.php');
$grouparray = $_POST['grouparray'];
$user_ID = '9';
$sql = "INSERT INTO wp_fb_manager (user_id, group_id) VALUES ($user_ID, $grouparray)";
$result=mysql_query($sql);
if ($result === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysql_error();
}
?>
You cannot send an array trough an ajax call.
First, use something like:
var idString = JSON.stringify(ids);
And use it: data: {grouparray: idString },
On the PHP side:
$array = json_decode($_POST['grouparray']);
print_r($array);
Using google maps, I have events saving to a database using mysqli. These events are then displayed as markers on the map and when clicked the relevant data is displayed in an info box (Name, date, etc). I want the option to delete an event event by deleting a row from the DB when the Remove (remove-event) button is clicked. The button is contained in the data displayed with the javascript:
var eventContent = $('<div class="event-info">' + '<h4 class="event-name">' + point.name + '</h4><hr>' +
'<span><h5>Date: </h5>' +
'<p class="event-date">' + point.edate + '</p></span>' +
'<p class="event-description">'+point.description+'</p>' +
'</span><button id="remove-event" name="remove-event" class="remove-event btn btn-danger btn-sm" onclick="tidy_maps.delete()" title="Remove Event">Remove Event</button>'+
'</div>');
// Display Event details on marker click
google.maps.event.addListener(event_markers[i], "click", function () {
infowindow.setContent(eventContent[0]);
infowindow.open(map, event_markers[i]);
The script that sends it to the php (removedata.php):
tidy_maps.delete = function() {
$.ajax({
type:'POST',
url:'removedata.php',
success:function(data) {
if(data) {
alert("Are you sure?");
}
else {
alert("ERROR!!!!");
}
}
});
}
The removedata.php is:
$con = mysqli_connect("localhost", "root", "password", "gmaps1");
if (!$con) {
die("Can not connect: " .mysql_error());
}
$sql = "DELETE FROM events WHERE id = 'id' ";
$query = mysqli_query($con, $sql);
if(mysqli_affected_rows($con)) {
echo "Record deleted successfully";
}
mysqli_close($con);
As it is, it does not delete the row in the DB, but when i change the line:
$sql = "DELETE FROM events WHERE id = 'id' ";
to a specific ID No. Example:
$sql = "DELETE FROM events WHERE id = '5' ";
And i run the removedata.php in the browser, it deletes the row with ID=5 from the DB. There seems to be no errors when the console when clicking the remove button so it must be sending to PHP script ok.
I would like when the Remove button is clicked that it asks are you sure and then it deletes that specific Row form the DB.
As far as I can tell you don't pass the ID of the row to be deleted.
You can send data two ways, either as a url parameter, or post it using the
data tag:
$.ajax({
type:'POST',
url:'removedata.php',
data: {id : 5}
});
Access the ID in removedata.php:
$id = intval($_POST["id"]);
$sql = "DELETE FROM events WHERE id = " . $id;
WHERE id = 'id' you need to remove the '' and add the $ symbol if you want id to be a variable.
Ok I've played around a little and amended the JS slightly:
tidy_maps.delete = function() {
var confirm_remove = confirm("Do You Want to Remove This Event?")
if(confirm_remove) {
$.ajax({
type:'POST',
url:'removedata.php',
});
window.location = "http://www.google.com/";
}
else {
alert("ERROR!!!!");
}
}
So when Confirm is YES, i threw in a redirect to Google just to see what happens. When YES is clicked in the confirm box, it redirects the page to Google but does not delete the row from the DB
Try this
var id = 5;
var request = $.ajax({
url:'removedata.php',
type: "POST",
data: "id="+id,
success: function(data){
console.log(data);
}
});
get post value in removedata.php
//get post value
$id = intval($_POST["id"]);
$sql = "DELETE FROM events WHERE id = " . $id;
I am trying to populate a drop down list using jquery and ajax.
Here's what my code looks like.
<script>
$(document).ready(function(){ //This script uses jquery and ajax it is used to set the values in
$("#day").change(function(){ // the time field whenever a day is selected.
var day=$("#day").val();
var doctor=$("#doctor").val();
$.ajax({
type:"post",
url:"time.php",
data:"day="+day+"&doctor="+doctor,
success:function(data){
$("#time").html(data);
}
});
});
});
</script>
Here's time.php
//some code for connecting to database
$doctor = $_POST['doctor'];
$day = $_POST['day'];
$query="SELECT * FROM schedule WHERE doctor='" .$doctor."'AND day='" .$day. "'";
$result = mysqli_query($con, $query);
echo"
<select name='timing' id='timing'>";
$i = 0; //Initialize the variable which passes over the array key values
$row = mysqli_fetch_assoc($result); //Fetches an associative array of the row
$index = array_keys($row); // Fetches an array of keys for the row.
while($row[$index[$i]] != NULL)
{
if($row[$index[$i]] == 1) {
$res = $index[$i];
echo jason_encode($res);
echo "<option value='" . $index[$i]."'>" . $index[$i] . "</option>";
}
$i++;
}
echo "</select>";
?>
This just puts list on time.php into a div time on my page. Is there some way I could grap individual options from the list on time .php and add them to a dropdown list on my page?
Thanks in Advance.
try:
success:function(data)
{
var option = '';
$.each(data.d, function(index, value) {
option += '<option>' + value.YourReturnParam + '</option>';
});
$('#yourDdlID').html(option);
}
<script>
$(document).ready(function(){ //This script uses jquery and ajax it is used to set the values in
$("#day").change(function(){ // the time field whenever a day is selected.
var day=$("#day").val();
var doctor=$("#doctor").val();
$.ajax({
type:"post",
url:"time.php",
data:"day="+day+"&doctor="+doctor,
success:function(data){
var jdata=eval('('+data+')');;
var str='';
for(var i=0;i<jdata.length;i++)
{
str.='<option>'+jdata[i]+'</option>';
}
$("#time").html(str);
}
});
});
});
time.php will return like
$res=array('a','b','v')
echo json_encode($res);
It would make it easier if the data variable that's used in the success callback is JSON or an array.
success:function(data)
{
var option = $('#time');
//Remove old options
option.empty();
//It makes it easier if you create an array to store all of the values that you want to
//populate the select tag with. I'm not sure if the data that's returned is in the form of an array or not
var newOptions = {'key1': 'value1','key2': 'value2', 'key3': 'value3'};
//Loop thru and change each option tag
$.each(newOptions, function(key, value) {
option.append($('<option></option>').attr('value', value).text(key));
});
}
And the html might look something like this, I'm guessing?
<select id="time">
<option value="val">Text</option>
<option value="val">More Text</option>
</select>