How to apply table classes to AJAX response table - javascript

I have a table to show data from the AJAX request made. Although the data is displaying for all the three radio choices made, my prob here is that as I have classes applied on the table that holds good for pagination purposes, the data displaying does not follow the classes applied on the table i.e. I have pagination that shows 10 records each time and then next page shows next 10 records. I am posting my code here and wish to have some insight or help over this.
<?php include 'blocks/headerInc.php' ; ?>
<?php require_once "phpmailer/class.phpmailer.php";?>
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
<?php
ob_start();
$errmsg = "" ;
$module_id = '';
$query = '';
$date_from = '';
$date_to = '';
$status ='';
$check ='';
$disabled='';
$row='';
$sqlQuery = "SELECT * FROM tbl_user WHERE type = 3 AND status = 0 AND registration_type = 0";
?>
<div class="container pagecontainer">
<!-- Static navbar -->
<div class="row row-offcanvas row-offcanvas-right">
<!--/.col-xs-12.col-sm-9-->
<div class="col-sm-3 col-md-3 sidebar" id="sidebar">
<div id="left_panel" class="clearfix left">
<?php include 'blocks/leftnavInc.php' ; ?>
</div>
</div>
<div class="col-xs-12 col-sm-9 page-right">
<div class="panel panel-primary">
<div class="panel-heading">Candidate Approval</div>
<div class="panel-body">
<div class="column col-sm-offset-0">
<form id="selection" method="GET" >
<input type='radio' name='users' value='unapproved' checked /> Unapproved Candidates
<input type='radio' name='users' value='approved' /> Approved Candidates
<input type='radio' id='show' name='users' value='all' /> All Candidates
<table id="example" class="table table-striped table-hover table-bordered dataTableReport dt-responsive nowrap" cellspacing="0" width="100%">
<thead>
<tr>
<th>S.No.</th>
<th>Email ID</th>
<th> Reference ID</th>
<th>Name</th>
<th>Mobile No.</th>
<th>Registration Date</th>
<th>Check for Approval
<input type="checkbox" id="select_all" name="all_check[]" <?php echo $disabled ;?> class="checkbox" value= "<?php //echo $row['id']; ?>"> </th>
</tr>
</thead>
<tbody id=datashow>
</tbody>
</table>
<input type="submit" name ="all_send" value="Approve" style="display: none; float: right;" id="one" class="btn btn-success">
</form>
</div>
</div>
</div>
<!--/row-->
</div>
<!--/.sidebar-offcanvas-->
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$('#selection').change
(
function()
{
var selected_value = $("input[name='users']:checked").val();
$.ajax
(
{
url: "approval_ajax.php",
type: "POST",
cache: false,
data: { selected_value : selected_value },
success: function(response)
{
console.log(response);
var len = response.length;
$("#datashow").empty();
for(var i=0; i<len; i++){
var id = response[i].id;
var email = response[i].email;
var employee_id = response[i].employee_id;
var first_name = response[i].first_name;
var middle_name = response[i].middle_name;
var last_name = response[i].last_name;
var mobile = response[i].mobile;
var created_on = response[i].created_on;
var disabled = response[i].disabled;
var users = response[i].users;
var tr_str =
"<tr>" +
"<td>" + (i+1) + "</td>" +
"<td>" + email + "</td>" +
"<td>" + employee_id + "</td>" +
"<td>" + first_name + " " + middle_name + " " + last_name + "</td>" +
"<td>" + mobile + "</td>" +
"<td>" + created_on + "</td>" +
"<td><input type='checkbox' name='check[]'" + disabled + "value= '" + id + "' class='checkbox' id='select_all' ></td>" +
"<input type='hidden' value='" + id + "' name='user_id' id='user_id' >" +
"</tr>" ;
$("#datashow").append(tr_str);
}
}
}
);
}
);
</script>
<script>
$(function() {
$('input[name="check[]"]').click(function() {
var checkedChbx = $('[type=checkbox]:checked');
if (checkedChbx.length > 0) {
$('#one').show();
} else {
$('#one').hide();
}
});
});
$(document).ready(function() {
var $submit = $("#one");
$submit.hide();
var $cbs = $('input[name="all_check[]"]').click(function() {
$('input[name="check[]"]').prop('checked',$(this).is(":checked"));
$submit.toggle($(this).is(":checked")); //use this to get the current clicked element
});
});
</script>
<script type="text/javascript">
var select_all = document.getElementById("select_all"); //select all checkbox
var checkboxes = document.getElementsByClassName("checkbox"); //checkbox items
//select all checkboxes
select_all.addEventListener("change", function(e){
for (i = 0; i < checkboxes.length; i++) {
checkboxes[i].checked = select_all.checked;
}
});
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('change', function(e){ //".checkbox" change
//uncheck "select all", if one of the listed checkbox item is unchecked
if(this.checked == false){
select_all.checked = false;
}
//check "select all" if all checkbox items are checked
if(document.querySelectorAll('.checkbox:checked').length == checkboxes.length){
select_all.checked = true;
}
});
}
</script>
<script>
// set users via PHP
var users = "<?php if (isset($_POST['users'])) echo $_POST['users']; ?>";
// update the HTML without interfering with other scripts
(function(users){
// check if PH
if (users.length) {
// update the radio option...
var inputTag = document.querySelector('input[value="'+users+'"]');
if (inputTag)
inputTag.checked = true;
// if users is "all"
// hide the last TD of every column
if (users == "all") {
var lastTh = document.querySelector('tr th:last-child');
lastTh.style.display = "none";
var allLastTds = document.querySelectorAll('td:last-child');
for (var i = 0; i< allLastTds.length; i++) {
allLastTds[i].style.display="none";
}
}
if (users == "approved") {
thInputTag = document.getElementById("select_all");
thInputTag.setAttribute("disabled", true);
}
var form = document.querySelector("form");
var inputName = document.querySelectorAll('input[name="users"]');
for (var j=0; j<inputName.length; j++)
inputName[j].onclick=function(){
form.submit();
};
}
})(users);
</script>
<?php include 'blocks/footerInc.php'; ?>
approval_ajax.php:
<?php
session_start();
require("../includes/config.php");
require("../classes/Database.class.php");
$db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
$return_arr = array();
$status='';
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$value = filter_input(INPUT_POST, "selected_value");
if (isset($value))
{
$users = $value;
}
else
{
$users='';
}
switch ($users)
{
case "all":
$sqlQuery = "SELECT * FROM tbl_user WHERE type =3";
break;
case "approved":
$sqlQuery = "SELECT * FROM tbl_user WHERE type =3 AND status =1";
break;
}
$sq = $db->query($sqlQuery);
if ($db->affected_rows > 0)
{
while ($row = mysql_fetch_array($sq))
{
$disabled = '';
if ($status == '1')
{
$disabled = "disabled = 'disabled' checked='checked' ";
}
$id = $row['id'];
$email = $row['email'];
$employee_id = $row['employee_id'];
$first_name = $row['first_name'];
$middle_name = $row['middle_name'];
$last_name = $row['last_name'];
$mobile = $row['mobile'];
$created_on1 = $row['created_on'];
$created_on = date("d-m-Y", strtotime($created_on1));
$return_arr[] = array("id" => $id,
"email" => $email,
"employee_id" => $employee_id,
"first_name" => $first_name,
"middle_name" => $middle_name,
"last_name" => $last_name,
"mobile" => $mobile,
"created_on" => $created_on
"disabled" => $disabled
);
}
}
header('Content-Type: application/json', true, 200);
echo json_encode($return_arr);
}

Well i think that id should be in quotation but in your code <tbody id=datashow> doesn't having any quotation may be you can change it like below
<tbody id="datashow">

Related

How can I perform remove to cart and update cart without page refresh

i have a simple code to add items to cart, when a user removes items to cart the page refreshes and that makes it scroll back to the top. updating quantity also does the same. I belive i can have these functions work without page refresh but i dont know how to execute this. here is my cart code
<?php
session_start();
// check if the delete_id is passed via the URL
if(isset($_GET['delete_id'])) {
$delete_id = (int)$_GET['delete_id'];
// search for the product to delete
foreach($_SESSION['cart'] as $key => $product) {
if($product['id'] === $delete_id) {
unset($_SESSION['cart'][$key]);
}
}
}
// check if the update_id and quantity are passed via the URL
if(isset($_GET['update_id']) && isset($_GET['quantity'])) {
$update_id = (int)$_GET['update_id'];
$quantity = (int)$_GET['quantity'];
// search for the product to update
foreach($_SESSION['cart'] as $key => $product) {
if($product['id'] === $update_id) {
if(isset($product['quantity'])) {
$_SESSION['cart'][$key]['quantity'] = $quantity;
} else {
$_SESSION['cart'][$key]['quantity'] = 1;
}
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Cart</title>
</head>
<body>
<!-- Header menu with logo, about us, and cart menu -->
<div id="header">
<div id="logo">Logo</div>
<div id="test">
products Page
</div>
<div id="about-us">About Us</div>
<div id="cart-menu">
Cart (<?=count($_SESSION['cart'])?>)
</div>
</div>
<!-- Cart list -->
<div id="cart-list">
<?php
if (empty($_SESSION['cart'])) {
echo '<p>Your cart is empty</p>';
} else {
$total = 0;
foreach($_SESSION['cart'] as $product) {
echo $product['name']. " <br>";
echo '<button type="button" onclick="decrementQuantity('.$product['id'].')">-</button>';
echo '<span id="product-'.$product['id'].'-quantity">'.(isset($product['quantity']) ? $product['quantity'] : 1).'</span>';
echo '<button type="button" onclick="incrementQuantity('.$product['id'].')">+</button>';
$subtotal = $product['price'] * (isset($product['quantity']) ? $product['quantity'] : 1);
echo '<p>Subtotal: $<span id="product-'.$product['id'].'-subtotal">'.number_format($subtotal,2).'</span></p>';
$total += $subtotal;
echo '<p><button type="button" onclick="removeFromCart('.$product['id'].')">Remove Item from Cart</button></p>';
echo '<hr>';
}
echo '<p>Total: $<span id="total">'.number_format($total,2).'</span></p>';
}
?>
</div>
<script>
function incrementQuantity(id) {
var currentQuantity = parseInt(document.getElementById('product-' + id + '-quantity').innerHTML);
var newQuantity = currentQuantity + 1;
updateQuantity(id, newQuantity);
}
function decrementQuantity(id) {
var currentQuantity = parseInt(document.getElementById('product-' + id + '-quantity').innerHTML);
if(currentQuantity > 1) {
var newQuantity = currentQuantity - 1;
updateQuantity(id, newQuantity);
}
}
function updateQuantity(id, value) {
var url = "cart.php?update_id=" + id + "&quantity=" + value;
// Change the displayed quantity
document.getElementById('product-' + id + '-quantity').innerHTML = value;
// Update the subtotal
var price = parseFloat(document.getElementById('product-' + id + '-subtotal').innerHTML) / parseInt(document.getElementById('product-' + id + '-quantity').innerHTML);
document.getElementById('product-' + id + '-subtotal').innerHTML = price * value;
updateTotal();
window.location.href = url;
}
function removeFromCart(id) {
var url = "cart.php?delete_id=" + id;
window.location.href = url;
}
function updateTotal() {
var total = 0;
var subtotals = document.getElementsByClassName('product-subtotal');
for (var i = 0; i < subtotals.length; i++) {
total += parseFloat(subtotals[i].innerHTML);
}
document.getElementById('total').innerHTML = total;
}
</script>
</body>
</html>
what i have read is i should add event listeners to the buttons and use $.ajax() method... I am not so good in coding therefore i cant implement this so i dont even know if it will work
<?php
session_start();
// check if the delete_id is passed via the URL
if(isset($_GET['delete_id'])) {
$delete_id = (int)$_GET['delete_id'];
// search for the product to delete
foreach($_SESSION['cart'] as $key => $product) {
if($product['id'] === $delete_id) {
unset($_SESSION['cart'][$key]);
echo "success";die;
}
}
}
// check if the update_id and quantity are passed via the URL
if(isset($_GET['update_id']) && isset($_GET['quantity'])) {
$update_id = (int)$_GET['update_id'];
$quantity = (int)$_GET['quantity'];
// search for the product to update
foreach($_SESSION['cart'] as $key => $product) {
if($product['id'] === $update_id) {
if(isset($product['quantity'])) {
$_SESSION['cart'][$key]['quantity'] = $quantity;
} else {
$_SESSION['cart'][$key]['quantity'] = 1;
}
echo "success";die;
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Cart</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
<div id="header">
<div id="logo">Logo</div>
<div id="test">
products Page
</div>
<div id="about-us">About Us</div>
<div id="cart-menu">
Cart (<?=count($_SESSION['cart'])?>)
</div>
</div>
<!-- Cart list -->
<div id="cart-list">
<?php
if (empty($_SESSION['cart'])) {
echo '<p>Your cart is empty</p>';
} else {
$total = 0;
foreach($_SESSION['cart'] as $product) {
echo "<div class='product product-".$product['id']."'>";
echo $product['name']. " <br>";
echo '<input type="hidden" id="product-'.$product['id'].'-price" value="'.$product['price'].'">';
echo '<button type="button" onclick="decrementQuantity('.$product['id'].')">-</button>';
echo '<span id="product-'.$product['id'].'-quantity">'.(isset($product['quantity']) ? $product['quantity'] : 1).'</span>';
echo '<button type="button" onclick="incrementQuantity('.$product['id'].')">+</button>';
$subtotal = $product['price'] * (isset($product['quantity']) ? $product['quantity'] : 1);
echo '<p>Subtotal: $<span id="product-'.$product['id'].'-subtotal" class="subtotals">'.number_format($subtotal,2).'</span></p>';
$total += $subtotal;
echo '<p><button type="button" onclick="removeFromCart('.$product['id'].')">Remove Item from Cart</button></p>';
echo '<hr></div>';
}
echo '<p>Total: $<span id="total">'.number_format($total,2).'</span></p>';
}
?>
</div>
<script>
function incrementQuantity(id) {
var currentQuantity = parseInt(document.getElementById('product-' + id + '-quantity').innerHTML);
var newQuantity = currentQuantity + 1;
updateQuantity(id, newQuantity);
}
function decrementQuantity(id) {
var currentQuantity = parseInt(document.getElementById('product-' + id + '-quantity').innerHTML);
if(currentQuantity > 1) {
var newQuantity = currentQuantity - 1;
updateQuantity(id, newQuantity);
}
}
function updateQuantity(id, value) {
var $proC = $('.product.product-' + id );
var product_price = $('#product-'+id+'-price').val();
$proC.find('button').attr("disabled","disabled");
var url = "cart.php?update_id=" + id + "&quantity=" + value;
$.ajax({
url:url,
type:'GET',
success:function(response){
$proC.find('button').removeAttr("disabled");
if($.trim(response) == 'success'){
document.getElementById('product-'+id+'-quantity').innerHTML = value;
document.getElementById('product-'+id+'-subtotal').innerHTML = product_price * value;
}else{
alert("Something went wrong.try again..");
}
updateTotal();
},
error:function(err){
$proC.find('button').removeAttr("disabled");
alert(err);
}
})
}
function removeFromCart(id) {
var url = "cart.php?delete_id=" + id;
$.ajax({
url:url,
type:'GET',
success:function(response){
if($.trim(response) == 'success'){
$('.product.product-'+id).remove();
alert("Product removed.");
}else{
alert("Something went wrong.try again..");
}
},
error:function(err){
alert(err);
}
})
}
function updateTotal() {
var total = 0;
var subtotals = document.getElementsByClassName('subtotals');
for (var i = 0; i < subtotals.length; i++) {
total += parseFloat(subtotals[i].innerHTML);
}
document.getElementById('total').innerHTML = total;
}
</script>
</body>
</html>

Export table to csv with multiple dropdowns

Im building a page with multiple selects inside each row, im using the select2 plugin to do that, my problem is: I did a lot of research but i sitll couldnt find a way of exporting this table to csv. I dont know if it is because of the placeholders that select2 plugin puts in each row or if its other error that i dont know that im making. I will leave some pics from my page and the script that i tried to do.
<form method="POST" action="select.php">
<table class="table-responsive table-striped table-bordered" id="example">
<thead>
<tr>
<th>Id</th>
<th>Nome Praia</th>
<th>Turno</th>
<?php
$x = 0;
$dias = array();
while ($row = mysqli_fetch_assoc($resultsett))
{
echo "<th>" . $row['dia'] . "</th>";
$dia = $row['dia'];
$id_dia = $row['id_dia'];
array_push($dias, $id_dia);
$x++;
}
?>
</tr>
</thead>
<tbody>
<?php
$sql_query = "SELECT * FROM tb_praia";
$resultset = mysqli_query($conn, $sql_query) or die("database error:" . mysqli_error($conn));
while ($res = mysqli_fetch_assoc($resultset))
{
$id_praia = $res['id_praia'];
$nome_praia = $res['nome_praia'];
$turno = $res['turno'];
?>
<tr id="<?php $id_praia; ?>">
<td> <?php echo $id_praia; ?></td>
<td><?php echo $nome_praia; ?> </td>
<td><?php echo $turno; ?></td>
<?php for ($i = 0;$i < $x;$i++)
{
if ($id_praia % 2 == 0){
$query = "SELECT tb_nadadores.id_nadador, nome from tb_disponibilidade inner JOIN
tb_nadadores on tb_disponibilidade.id_nadador=tb_nadadores.id_nadador
where id_dia = $dias[$i] and Tarde=1 order by id_nadador ASC";
}else{
$query = "SELECT tb_nadadores.id_nadador, nome from tb_disponibilidade inner JOIN
tb_nadadores on tb_disponibilidade.id_nadador=tb_nadadores.id_nadador
where id_dia = $dias[$i] and Manhã=1 order by id_nadador ASC ";
}
$resposta = mysqli_query($conn, $query);
echo (
'<td>
<select name="nadadores[]" size="1" class="form-select multiple-select" multiple>
<br>'
);
if (mysqli_num_rows($resposta) > 0)
{
while ($teste = mysqli_fetch_assoc($resposta))
{
$nadador = $teste['nome'];
$id_nadador = $teste['id_nadador'];
echo "<option value=$id_nadador>$nadador</option>";
}
echo '</select>';
}
else{
echo 'Não foram encontrados resultados!';
}
echo "<input type='hidden' name='dias[]' value=$dias[$i] >";
echo "<input type='hidden' name='turno' value=$turno >";
echo "<input type='hidden' name='id_praia' value=$id_praia >";
echo "<input type='hidden' name='nome_praia' value=$nome_praia>";
}
}
?>
</tr>
</tbody>
</table>
<input type="submit" name="enviar" value="Enviar">
</form>
$(document).ready(function() {
$(".multiple-select").select2({
maximumSelectionLength: 2,
width: 'resolve'
});
$('.multiple-select').on('select2:select', function (e) {
var {id} = e.params.data;
var { dia, praia, turno} = e.currentTarget.dataset
console.log({ dia, praia, id, turno});
$.post('data.php', { dia, praia, id, turno })
// console.log(data);
})
$('.multiple-select').on('select2:unselect', function (remove) {
var {id} = remove.params.data;
var { dia, praia, turno} = remove.currentTarget.dataset
$.post('remove.php', { dia, praia, id, turno })
console.log( { dia, praia, id, turno });
});
});
Export script
function downloadCSVFile(csv, filename) {
var csv_file, download_link;
csv_file = new Blob([csv], {type: "text/csv"});
download_link = document.createElement("a");
download_link.download = filename;
download_link.href = window.URL.createObjectURL(csv_file);
download_link.style.display = "none";
document.body.appendChild(download_link);
download_link.click();
}
document.getElementById("download-button").addEventListener("click", function () {
var html = document.querySelector("table").outerHTML;
htmlToCSV(html, "Horario_Definido.csv");
});
function htmlToCSV(html, filename) {
var data = [];
var rows = document.querySelectorAll("table tr");
for (var i = 0; i < rows.length; i++) {
var row = [], cols = rows[i].querySelectorAll("td, th");
for (var j = 0; j < cols.length; j++) {
row.push(cols[j].innerText);
}
data.push(row.join(","));
}
//to remove table heading
//data.shift()
downloadCSVFile(data.join("\n"), filename);
}

PHP $_POST can't read values set by jQuery val()

I created a little script which allows users to shadow some input values from other inputs. The JavaScript part is working fine, but now when I'm trying to send the form, it doesn't send it, saying that the field the value is copied to is empty. What's the problem here? Thanks!
$(document).ready(function()
{
$(":text").blur(function()
{
var input = $(this);
var id = input.attr("id");
var fieldname = "#".concat(id);
for (i = 0; i < fields.length; i++)
{
if (fields[i][4] == id)
{
var boxname = "#copy_".concat(fields[i][0]);
if ($(boxname).prop("checked"))
{
var fieldname2 = "#".concat(fields[i][0]);
$(fieldname2).val($(fieldname).val());
}
}
}
});
$(":checkbox").change(function()
{
var input = $(this);
var id = input.attr("id");
id = id.substring(id.indexOf("_") + 1, id.length);
var fieldname = "#".concat(id);
var checked = input.prop("checked");
$(fieldname).prop("disabled", checked);
var field = FindField(0, fields[FindField(0, id)][4]);
if (checked)
{
var fieldname2 = "#".concat(fields[field][0]);
$(fieldname).val($(fieldname2).val());
}
});
});
function FindField(index, value)
{
for (i = 0; i < fields.length; i++)
{
if (fields[i][index] == value) return i;
}
return -1;
}
The form (without some irrelevant stuff):
<form method="post" action="sendform.php">
<table>
<?php
foreach ($fields as $field)
{
if ($field[0] == "divider") echo('<tr><td colspan="2"><hr /></td></tr>');
else
{
switch ($field[2])
{
case FIELD_TEXT:
{
echo('<tr><td><label for="' . $field[0] . '">' . $field[1] . ': </label></td><td>');
if ($field[4] != "")
{
foreach ($fields as $field2)
{
if ($field2[0] == $field[4])
{
echo('<input type="checkbox" id="copy_' . $field[0] . '" title="Kopeeri väljalt "' . $field2[1] . '"" />');
}
}
}
echo('<input type="text" id="' . $field[0] . '" name="' . $field[0] . '" placeholder="' . $field[1] . '" /></td></tr>');
break;
}
}
}
}
?>
<tr><td colspan="2"><hr /></td></tr>
<tr>
<td colspan="2" style="text-align: center;">
<input type="submit" value="Saada avaldus" name="saadaavaldus" />
</td>
</tr>
</table>
</form>
A sample of the fields array:
var fields = <?php echo json_encode($fields); ?>
$fields = array
(
// ID/name label/placeholder type regex field copied from
array( "saatjanimi", "Teie täisnimi", FIELD_TEXT, "^[-,.'\s\pL]*\pL[-,.'\s\pL]\s+[-,.'\s\pL]*\pL[-,.'\s\pL]*$", ""),
array( "meiliaadress", "Teie meiliaadress", FIELD_TEXT, "^([\pL-.\d]+)#([\pL-.\d]+)((\.(\pL){2,63})+)$", ""),
array( "isanimi", "Lapse isa täisnimi", FIELD_TEXT, "^[-,.'\s\pL]*\pL[-,.'\s\pL]\s+[-,.'\s\pL]*\pL[-,.'\s\pL]*$", "saatjanimi")
);

Clear previous return data from DataBase in HTML using PHP+JSON+AJAX

I am doing Database project and I built Database and UI, the communication between the DB and the UI is made by PHP,JSON and AJAX.
In the Top 3 tab I am trying to bring the top 3 student with the highest grades, my plan was to use a dropdown options and pick each time another course and bring the top 3 each time. The code is working but not as I wanted.
It is always append the new results to the last results. If I am trying to bring another top 3 student it is append the new results to the last results and not clearing the previous data.
My code is :
Javascript:
$('#showCourse').click(function(){
console.log("showCourse");
var top3 = $('#top3').val();
var top3Table = $('#top3Table');
console.log(top3);
$.ajax({
type: "POST",
dataType:"json",
data: {"top3" : top3},
url: "jsonTop3.php",
cache: false,
success: function(data){
console.log("success");
console.log(data.length);
for (var i = 0; i < data.length; i++) {
var row = "<tr><td>" + data[i].student_id + "</td>" +
"<td>" + data[i].grade + "</td></tr>";
top3Table.append(row);
}
}
});
});
HTML:
<div class="container">
<div class="insertData" style="height:180px;">
<h3>Pick Course name:</h3>
<form class="form-horizontal">
<select class="form-control" id="top3" onchange="document.getElementById('text_content').value=this.options[this.selectedIndex].text">
<option>None</option>
<option>Operational Systems</option>
<option>Integrators</option>
<option>Web Development</option>
<option>Algebra</option>
<option>Chimestry</option>
<option>Biology</option>
<option>History</option>
<option>JAVA</option>
<option>Intro to Math</option>
<option>UNIX</option>
</select>
<input type="hidden" name="hid" id="text_content" value="">
</form>
<div class="rightButtons">
<button type="add" name="type" class="btn btn-success" id="showCourse">Show</button>
</div>
</div>
<div class="table">
<h2>Top 3 Table</h2>
<table class="table table-striped">
<thead>
</thead>
<tbody id = "top3Table">
</tbody>
</table>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
PHP:
<?php
function printStudents() {
$host="127.0.0.1";
$port=3306;
$user="root";
$password="root";
$dbname="courcessystem";
$con = new mysqli($host, $user, $password, $dbname, $port)
or die ('Could not connect to the database server' . mysqli_connect_error());
$sql = "SELECT * FROM reg_courses
ORDER BY course_id ASC";
$result = mysqli_query($con, $sql) or die("Error in Selecting " . mysqli_error($con));
$emparray = array();
while($row =mysqli_fetch_assoc($result)) {
$emparray[] = $row;
}
echo json_encode($emparray);
$con->close();
}
printStudents();
?>
use
success: function(data){
var row = '';
for (var i = 0; i < data.length; i++) {
row += "<tr><td>" + data[i].student_id + "</td>" +
"<td>" + data[i].grade + "</td></tr>";
}
top3Table.html(row);
}
instead of your success function
What about empty the table before appending rows?
$.ajax({
type: "POST",
dataType:"json",
data: {"top3" : top3},
url: "jsonTop3.php",
cache: false,
success: function(data){
console.log("success");
console.log(data.length);
top3Table.empty();
for (var i = 0; i < data.length; i++) {
var row = "<tr><td>" + data[i].student_id + "</td>" +
"<td>" + data[i].grade + "</td></tr>";
top3Table.append(row);
}
}

How to get $_POST working with my editable jquery table?

I have this editable html table that I've got working, so you can click the cells and edit the text, however I can't get it to post the values as well.
I know there's a problem with the 5 lines of code under the comment on script.js
test.php
<h2><u>Edit</u></h2>
<form action="ajax/name.php" name="edit_template_form" id="edit_template_form" method="post">
<?php print "<table border=\"1\" class=\"editableTable\">
<tr>
<th>Template Name</th>
<th>Template Description</th>
</tr>";
foreach($res as $row){
$temp_description = $row['template_description'];
echo "<tr>";
echo "<td id=\"edit_name\" name=\"edit_name\">". $row['template_name']. "</td>";
echo "<td id=\"edit_template\" name=\"edit_template\">". nl2br($temp_description). "</td>";
echo "<tr/>";
}
print "</table>"; ?>
</form>
<div id="template_edit"></div>
name.php
if (isset($_POST['edit_template'])) {
$template_edit = $db->escape($_POST['edit_template']);
$user = $db->escape($user);
$db->update('templates', array('template_description' => $template_edit), 'AND userID="'.$user.'"');
echo $_POST['edit_template'];
}
if (isset($_POST['edit_name'])) {
$template_name = $db->escape($_POST['edit_name']);
$user = $db->escape($user);
$db->update('templates', array('template_name' => $template_name), 'AND userID="'.$user.'"');
echo $_POST['edit_name'];
}
script.js
$(function () {
$("td").dblclick(function () {
var OriginalContent = $(this).text();
$(this).addClass("cellEditing");
$(this).html("<input type='text' value='" + OriginalContent + "' />");
$(this).children().first().focus();
$(this).children().first().keypress(function (e) {
if (e.which == 13) {
//POST values
var edit_template = $('#edit_template').val();
var edit_name = $('#edit_name').val();
$.post('ajax/name.php', {edit_name: edit_name, edit_template: edit_template}, function(data) {
$('div#template_edit').text(data);
});
var newContent = $(this).val();
$(this).parent().text(newContent);
$(this).parent().removeClass("cellEditing");
}
});
$(this).children().first().blur(function(){
$(this).parent().text(OriginalContent);
$(this).parent().removeClass("cellEditing");
});
});
});

Categories