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");
});
});
});
Related
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);
}
Hello there am trying to get the data from database using ajax posts but i didn't get any data properly. first column data is splinting in another columns(Member names are coming in image field and info field). Image also shared please check that. And also datatables are not working while fetching the data using Ajax. Help me out from this problem...
Thanks & Regards
<body>
<label>Party</label>
<select id='partydropdown' name='partydropdown' onchange="partyFunction();">
<option>--select a party--</option>
<?php
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
?>
<option value="<?php echo $row["Id"];?>">
<?php echo $row["PartyName"];?>
</option>
<?php }}?>
</select>
<div id="showhide"></div>
</body>
<script type="text/javascript">
function partyFunction(){
debugger;
$("#showhide").empty();
$("#showhide").html('');
$("#showhide").append("<table class='table table-bordered text-center table-responsive' border='1px' id='example'>"+
"<tr>"+
"<th>PartyMemberName</th>"+
"<th>Image</th>"+
"<th>Info</th>"+
"</tr>"+
"<tbody id='partyBody'>"+
"</tbody>"+
"</table>"
);
$postdata = {};
$postdata["Id"]=$("#partydropdown").val();
console.log($("#partydropdown").val());
$.post('test_data.php',$postdata,function (data) {
debugger;
console.log(data);
console.log(data["data"][0].candiateName);
$("#partyBody").empty();
$("#partyBody").html('');
console.log(data["data"]);
console.log(data["data"].length);
for(var i=0; i<data["data"].length; i++){
if(data["data"][i].candiateName != null){
$("#partyBody").append("<tr>"+
"<td id='resdata"+i+"'></td>"+
"<td id='resdata1"+i+"' ></td>"+
"<td id='resdata2"+i+"'></td>"+
"</tr>");
$("#resdata"+i).text(data["data"][i].candiateName);
$("#resdata1"+i).append("<img id='photo"+i+"'>");
$("#resdata2"+i).text(data["data"][i].Background);
$("#photo"+i).attr('src', 'http://aptsvotes.com/wp-content/themes/apts2019/img'+data["data"][i].Photo );
}
}
});
};
</script>
here is the test_data.php code
<?php
include_once "conn.php";
include_once "voterdbclass.php";
session_start();
$tbl_name2="Parties";
$dbObj = new Database1();
$values1 = array("all");
$querys = "SELECT c1.CandidateName,c1.Photo,c1.Background ,c1.Type FROM aptsv1_votes.Parties p1 LEFT JOIN aptsv1_votes.Candidates c1 ON c1.CurrentPartyId = p1.Id where p1.Id ='" . $_POST['Id'] . "' limit 21";
$res = $dbObj->SelectRecord($tbl_name2,$values1,"","$querys");
$data=array();
$i=0;
while ($rs = $res->fetch_array(MYSQLI_ASSOC)) {
$data[$i]['candiateName']=$rs['CandidateName'];
$data[$i]['Photo']=$rs['Photo'];
$data[$i]['Background']=$rs['Background'];
$i++;
}
$json_array= array(
"data" =>$data
);
echo json_encode($json_array);
?>
for(var i=0; i<data["data"].length; i++){
if(data["data"][i].candiateName != null){
var imge = data["data"][i].Photo;
var name = data["data"][i].candiateName;
var bg = data["data"][i].Background;
$("#partyBody").append("<tr>"+
"<td id='resdata" + i + "'>" + name+"</td>"+
"<td id='resdata1" + i + "' ><img id= 'photo" + i + "' src='http://aptsvotes.com/wp-content/themes/apts2019/img'" + imge+"></td>"+
"<td id='resdata2" + i + "'>" + bg+"</td>"+
"</tr>");
}
}
You have to parse JSON data into the first script. While ajax result you posting with json_encode, I found missing
var data = $.parseJSON(data);
console.log(data["data"].length);
into code
$.post('test_data.php',$postdata,function (data) {
// debugger;
console.log(data);
var data = $.parseJSON(data); // Add this line in your code and verify
console.log(data["data"].length);
Thank you!
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">
I am trying to sort data that pulls with an ajax get request, how do i get all the checked categories instead of only the one pressed, would be nice to get both 2/3 if both are checked?
Currently I insert a number in the database under "kategori" and they should be sorted through these numbers?
how do i get both queries in the url?
Example here : http://xch07.wi2.sde.dk/sandbox/SQL/
HTML
<form>
<input class="kategorier" type="checkbox" value="1">Kat 1<br>
<input class="kategorier" type="checkbox" value="2">Kat 2 <br>
<input class="kategorier" type="checkbox" value="3">Kat 3
</form>
<br>
<div id="txtHint">Person info will be listed here...
</div>
JS/AJAX
var kategorier = document.getElementsByClassName("kategorier");
var kategorierLength = kategorier.length;
for(let i=0; i < kategorierLength ;i++){
kategorier[i].addEventListener('click', function(){
showUser(this.value);
});
};
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","index.php?page=getuser&kategori="+str ,true);
xmlhttp.send();
}
}
PHP
$kategori = intval($_GET['kategori']);
mysqli_select_db($dbCon,"ajax_demo");
$sql="SELECT * FROM db_test WHERE kategori = $kategori ";
$result = $dbCon->query($sql);
echo "<table>
<tr>
<th>Id</th>
<th>Navn</th>
<th>Efternavn</th>
<th>email</th>
<th>Kategori</th>
</tr>";
while($row = $result->fetch_object()) {
$id = $row->id;
$navn = $row->navn;
$efternavn = $row->efternavn;
$email = $row->email;
$kategori = $row->kategori;
echo "<tr>";
echo "<td>" . $id . "</td>";
echo "<td>" . $navn . "</td>";
echo "<td>" . $efternavn . "</td>";
echo "<td>" . $email . "</td>";
echo "<td>" . $kategori . "</td>";
echo "</tr>";
}
echo "</table>";
<script type="text/javascript">
window.onload = function () {
var kategorier = document.getElementsByClassName("kategorier");
var kategorierLength = kategorier.length;
for(var i=0; i < kategorierLength ;i++){
kategorier[i].addEventListener('click', function(){
var checked = '';
for (var k = 0; k < kategorierLength; k++) {
if (checked) {
var separator = ',';
} else {
var separator = '';
}
if (kategorier[k].checked) {
checked += separator+kategorier[k].value;
}
}
alert(checked);
if (checked) {
showUser(checked);
}
});
}
}
After that you need to change your query and use IN statement like below.
$kategori = $_GET['kategori'];
mysqli_select_db($dbCon,"ajax_demo");
$sql="SELECT * FROM db_test WHERE kategori IN ($kategori)";
$result = $dbCon->query($sql);
I've a html checkbox which select all checkbox after click. But unfortunately it's not working. What's the problem in here ?
javascript Code:
<script language="JavaScript">
function toggle(source) {
checkboxes = document.getElementsByName('contact_no');
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = source.checked;
}
}</script>
Php code:
echo "<table width='100%' cellpadding='0' cellspacing='0'>";
echo "<tr>";
echo "<td class='tdhead' valign='top' width='100'><b>Contact Name</b></td>";
echo "<td class='tdhead' valign='top' width='100'><b>Contact
Number</b>";
echo '<input type="checkbox" onClick="toggle(this)" /> Toggle
All<br/>';
echo "</tr>";
while($row = mysqli_fetch_array($result))
{
$gid = $row['gid'];
$contact_name = $row['contact_name'];
$contact_no = $row['contact_no'];
echo "<tr>";
echo "<td class='tdhead2' valign='top'>$contact_name</td>";
echo "<td class='tdhead2' ><input type='checkbox' value='$gid' name='contact_no[]''
/> $contact_no</td>";
echo "</tr>";
}
echo "</table>";
The name on each of your elements is: contact_no[] but in your JS code, you getElementsByName('contact_no') - add [] to the getElementsByName call.
for a safety, you should handle event object like code below
<script type="text/javascript">
function toggle(evt) {
evt = window.event || evt;
var source = evt.srcElement || evt.currentTarget
checkboxes = document.getElementsByName('contact_no');
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = source.checked;
}
}
</script>
<script language="JavaScript">
function toggle(source)
{
checkboxes = document.getElementsByName('contact_no');
for(var i=0, n=checkboxes.length;i<n;i++)
{
contact_no[i].checked = source.checked;
}
}
</script>
One another solution, you can add Id attribute on the main check box from which you want to perform select all action and make the same as class attribute of other check boxes.
E.g.
$(document).ready(function(){
$('.selectall').change(function({
var id = $(this).attr('id');
if ($(this)is(":checked")) {
$("." + id).attr('checked','checked');
} else {
$("." + id).attr('checked','');
}
}))
})
I hope this code helps you