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);
}
Related
I've been working on a function in a PHP system where I can filter the records and then export it to Excel that has a template using PHPSpreadSheet. My problem is that I don't know how to retrieve the filtered records as said in the title above. I think I'm missing something here in my code. This is my code in fetching the records from database into table.
<?php
$conn = mysqli_connect("localhost", "root", "", "db_ims");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM tbl_par";
$result = mysqli_query($conn, $sql);
echo "<table id='myTable'>";
echo "<thead><tr><th>Article</th>
<th>Description</th>
<th>Property Number</th>
</tr></thead>";
echo "<tbody>";
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row['article'] . "</td>";
echo "<td>" . $row['description'] . "</td>";
echo "<td>" . $row['propertyNumber'] . "</td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
// Close the database connection
mysqli_close($conn);
?>
<form action="" method="POST">
<input type="text" id="myInput" onkeyup="filterTable()" placeholder="Search...">
<input type="submit" id="generate" name="generate" value="Submit">
</form>
This is my code in filtering the records:
<script>
function filterTable() {
// Declare variables
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
// Loop through all table rows, and hide those who don't match the search query
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td");
for (var j = 0; j < td.length; j++) {
txtValue = td[j].textContent || td[j].innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
break;
} else {
tr[i].style.display = "none";
}
}
}
}
</script>
Lastly, this is the code in exporting the filtered table into excel using PHPSpreadSheet:
<?php
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
if (isset($_POST['generate'])) {
$spreadsheet = IOFactory::load('Template.xls');
//This is the part where I don't know what to put.
$data = array();
$worksheet = $spreadsheet->getActiveSheet();
$row = 10; // Start inserting data from row 10
foreach ($data as $item) {
$worksheet->setCellValue('A'.$row, $item['article']);
$worksheet->setCellValue('B'.$row, $item['description']);
$worksheet->setCellValue('C'.$row, $item['propertyNumber']);
// ...
$row++;
}
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('exported_file.xlsx');
}
?>
I tried every possible way that I know but still didn't got my expected result.
If you want to submit the values you need to echo the table inside the form and have something to submit - a hidden field for example - then you can add disabled to the fields you do not want to submit
const hide = txtValue.toUpperCase().indexOf(filter) === -1 : true : false;
tr[i].style.display = hide ? "none" : "";
tr[i].querySelector("[type=hidden]").disabled = hide;
I strongly suggest you use AJAX here instead.
I have this pagination written in php that works fine, but I want to use ajax to implement this so that the pages won't have to reload every time a link is clicked. I have gone through previous questions asked on this same topic here on SO and other blogs but I'm not getting it right.
Here's my pagination code in nav_tbl.php
if(!empty($_POST['rownum'])){
$rowno = $_POST['rownum'];
//get current page
$currentpage = isset($_POST['currentpage']) ? $_POST['currentpage'] : 1;
$no_of_records_per_page = $rowno;
$setoff = ($currentpage - 1) * $no_of_records_per_page;
//get total number of records in database
$sqlcount = "SELECT *FROM evatbl WHERE RegNo = ?";
$stmt = $con->prepare($sqlcount);
$stmt->bind_param("s", $pregno);
$pregno = $_SESSION['regno'];
$stmt->execute();
$result = $stmt->get_result();
$num_rows = $result->num_rows;
$totalpages = ceil($num_rows/$no_of_records_per_page);
//query for pagination
$sqllimit = "SELECT *FROM evatbl WHERE RegNo = ? ORDER BY CourseTitle LIMIT $setoff, $no_of_records_per_page";
if ($stmt = $con->prepare($sqllimit))
{
$stmt = $con->prepare($sqllimit);
$stmt->bind_param("s", $pregno);
$pregno = $_SESSION['regno'];
$stmt->execute();
$result = $stmt->get_result();
$num_rows = $result->num_rows;
if ($num_rows>0)
{
$count = 1;
echo "<table id='t01' class='table' width='100%'>
<tr id='tblhead'>
<th>SN</th>
<th>Course Title</th>
<th>Course Code</th>
<th>Credit Unit</th>
<th>Course Lecturer</th>
<th>Rating(%)</th>
</tr>";
while($row = $result->fetch_assoc())
{
$ccode = $row['CourseCode'];
$ctitle = $row['CourseTitle'];
$cunit = $row['CreditUnit'];
$clec = $row['CourseLecturer'];
$crate = $row['Rating'];
echo "
<tr>
<td>$count</td>
<td>$ctitle</td>
<td>$ccode</td>
<td>$cunit</td>
<td>$clec</td>
<td>$crate</td>
</tr>";
$count++;
}
echo "</table>";
}
else{
echo "<p style='color:darkred;margin-bottom:0;'>Oops! No records found.</p>";
}
?><br>
<div class="nav_div" id="nav_div">
<label for="navno">Navigate pages: </label>
<?php
//First Page Button
if($currentpage > 1)
{
echo "<a class='nav_a' id='first' href='view_eva.php?limit=".$rowno."¤tpage=".(1)."' title='First'><<</a>";
}
//Previous Page Button
if($currentpage >= 2)
{
echo "<a class='nav_a' id='prev' href='view_eva.php?limit=".$rowno."¤tpage=".($currentpage - 1)."' title='Previous'><</a>";
}
?>
<select class='navno' name='navno' id='navno' onchange="pageNav(this)">
<?php
//Link to available number of pages with select drop-down
for($i = 1; $i <= $totalpages; $i++)
{
echo "<option class='bold'";
if ($currentpage==$i)
{
echo "selected";
}
echo " value='view_eva.php?limit=".$rowno."¤tpage=".$i."'>".$i."</option>";
}
?>
</select>
<?php
//Next Page Button
if($currentpage < $totalpages)
{
echo "<a class='nav_a' id='next' href='view_eva.php?limit=".$rowno."¤tpage=".($currentpage + 1)."' title='Next'>></a>";
}
//Last Page Button
if($currentpage <= $totalpages - 1)
{
echo "<a class='nav_a' id='last' href='view_eva.php?limit=".$rowno."¤tpage=".($currentpage = $totalpages)."' title='Last'>>></a>";
}
?>
</div>
<?php
}
else
{
echo "<p style='color:darkred;margin-bottom:0;'>Oops! No records found.</p>";
}
?>
And here's the Ajax code to set number of rows to display per page using a select dropdown option
$(document).on('change', '#rowno', function(e){
e.preventDefault();
var rownum = $('#rowno').val();
if($('#check').is(":checked")) {
$('#check').prop('checked',false);
}
$.ajax({
type: 'POST',
url: 'navtbl.php',
cache: false,
async: false,
data: {
rownum : rownum
},
success: function(datalog){
console.log(datalog);
$("#display_table").html(datalog).show();
},
error: function(datalog){
swal("Oops.", "An error occured! Unable to fetch result.", "error");
}
});
});
// Call Function to load and display table on Page Load
function Ini_loadTable(){
var rownum = $('#rowno').val();
$.ajax({
type: 'POST',
url: 'navtbl.php',
cache: false,
async: false,
data: {
rownum : rownum
},
success: function(datalog){
console.log(datalog);
$("#display_table").html(datalog).show();
},
error: function(datalog){
swal("Oops.", "An error occured! Unable to fetch result.", "error");
}
});
}
Please, any help will be much appreciated. 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">
My JavaScript/AJAX prints comments. It's all good, until I want to insert/get more than one comment. It duplicates itself. This feels like a nesting/missed parenthesis problem in my code, but I can't be able to find it...
My JS code:
$(document).ready(function(){
var url = 'comment-get.inc.php';
$.getJSON(url, function(data) {
$.each(data, function(index, item) {
var t = '';
t += '<div class="comment_holder" id="_'+item.id+'">';
t += '<div class="user"> <img src="src/img/page3_img7.jpg" alt="" class="img_inner fleft">';
t += '<div class="extra_wrapper">';
t += ''+item.username+'<br>';
t += ''+item.date+'<br>';
t += '<button class="button2" type="button" id="'+item.id+'">Delete</button>';
t += '</div></div>';
t += ''+item.message+'<br><br>';
t += '</div>';
$('.comment_holder').prepend(t);
add_delete_handlers();
});
});
add_delete_handlers();
$('#postButton').click(function(){
comment_post_btn_click();
});
function comment_post_btn_click()
{
//text in textarea with username, page and date
var _username = $('#postUsername').val();
var _page = $('#postPage').val();
var _date = $('#postDate').val();
var _message = $('#postMessage').val();
if(_message.length > 0)
{
//proceed with ajax callback
$('#postMessage').css('border', '1px solid #ABABAB');
$.post("comment-set.inc.php",
{
task : "comment-set",
username : _username,
page : _page,
date : _date,
message : _message
}
).success(
function(data)
{
//Task: Insert html into the div
comment_set(jQuery.parseJSON(data));
console.log("ResponseText: " + data);
});
}
else
{
//text in area is empty
$('#postMessage').css('border', '1px solid #FF0000');
console.log("Comment is empty");
}
//remove text after posting
$('#postMessage').val("");
}
function add_delete_handlers()
{
$('.button2').each(function()
{
var btn = this;
$(btn).click(function()
{
comment_delete(btn.id);
});
});
}
function comment_delete(_id)
{
$.post("comment-del.inc.php",
{
task : "comment-del",
id : _id
}
).success(
function(data)
{
$('#_' + _id).detach();
});
}
function comment_set(data)
{
var t = '';
t += '<div class="comment_holder" id="_'+data.comment.id+'">';
t += '<div class="user"> <img src="src/img/page3_img7.jpg" alt="" class="img_inner fleft">';
t += '<div class="extra_wrapper">';
t += ''+data.comment.username+'<br>';
t += ''+data.comment.date+'<br>';
t += '<button class="button2" type="button" id="'+data.comment.id+'">Delete</button>';
t += '</div></div>';
t += ''+data.comment.message+'<br><br>';
t += '</div>';
$('.comment_holder').prepend(t);
add_delete_handlers();
}
});
Comments.php:
<?php
class Comments {
public function set($message, $username, $date, $page) {
$connect = mysqli_connect('localhost', 'root', '', 'trdb');
$sql = "INSERT INTO comments VALUES ('', '$username', '$page', '$date', '$message')";
$query = mysqli_query($connect, $sql);
if($query){
$std = new stdClass();
$std->id = mysqli_insert_id($connect);
$std->message = $message;
$std->username = $username;
$std->date = $date;
$std->page = $page;
return $std;
}
return null;
}
public function del($id) {
$connect = mysqli_connect('localhost', 'root', '', 'trdb');
$sql = "DELETE FROM comments WHERE id = $id";
$query = mysqli_query($connect, $sql);
if($query)
{
return true;
}
}
}
?>
Comment-get.inc.php:
<?php
$page = htmlentities("/index.php?page=maplepancakes", ENT_QUOTES);
$connect = mysqli_connect('localhost', 'root', '', 'trdb');
$sql = "SELECT * FROM comments WHERE page='$page' ORDER BY id DESC";
$result = $connect->query($sql);
$data = array();
while ($row = $result->fetch_assoc()) {
$row_data = array(
'id' => $row['id'],
'username' => $row['username'],
'date' => $row['date'],
'message' => $row['message']
);
array_push($data, $row_data);
}
?>
<?php
echo json_encode($data);
?>
Comment-set.inc.php:
<?php
if(isset($_POST['task']) && $_POST['task'] == 'comment-set'){
$username = $_POST['username'];
$date = $_POST['date'];
$page = $_POST['page'];
$message = $_POST['message'];
require_once 'comments.php';
if(class_exists('Comments')){
$userInfo = $username;
$commentInfo = Comments::set($message, $username, $date, $page);
$std = new stdClass();
$std->user = $userInfo;
$std->comment = $commentInfo;
echo json_encode($std);
}
}
?>
Picture of the problem (json_encode in the bottom of the picture containing 3 comments):
your comments div container has class .comment_holder so each time with new comment you prepend to all class's so create comment container with unique id an prepend to this. like this $('#comment_container').prepend(t); this with work.
I am trying to make a calender using php according to a video tutorial from youtube. I m doing just what they do but there is a difference from their table.I can't find my mistake...any body help please....give the code and the picture of this....
This is my calender-
This is the tutorial calender-
<html>
<head>
<title>Calender</title>
</head>
<body>
<?php
if(isset($_GET['day']))
{
$day = $_GET['day'];
}else
{
$day = date("j");
}
if(isset($_GET['month']))
{
$month = $_GET['month'];
}else{
$month = date("n");
}
if(isset($_GET['year']))
{
$year = $_GET['year'];
}else{
$year = date("Y");
}
//calender variable-----------
$currentTimeStamp = strtotime($year-$month-$day);
$monthName = date("F",$currentTimeStamp);
$numDays = date("t",$currentTimeStamp);
$counter = 0;
?>
<table border = "1">
<tr>
<th><input style = "width : 50px"type = "button" value = "<" name = "prevbutton"></input></th>
<th colspan = "5"><?php echo $monthName.", ".$year?></th>
<th><input style = "width : 50px" type = "button" value = ">" name = "nextbutton"></input></th>
</tr>
<tr>
<td width = "50px">Sun</td>
<td width = "50px">Mon</td>
<td width = "50px">Tue</td>
<td width = "50px">Wed</td>
<td width = "50px">Thu</td>
<td width = "50px">Fri</td>
<td width = "50px">Sat</td>
</tr>
<?php
echo "<tr>";
for($i = 1;$i<$numDays+1;$i++,$counter++)
{
$timeStamp = strtotime($year-$month-$i);
if($i == 1)
{
$firstDay = date('w', $timeStamp);
for($j = 0;$j<$firstDay;$j++,$counter++)
{
echo "<td> </td>";
}
}
if($counter%7==0)
{
echo "</tr><tr>";
}
}
echo "</tr>";
?>
</table>
</body>
You had 3 bugs in php code
echo "<tr>";
for($i = 1;$i<$numDays+1;$i++,$counter++)
{
$timeStamp = strtotime($year.'-'.$month.'-'.$i);// it should be string
if($i == 1)
{
$firstDay = date('w', $timeStamp);
for($j = 0;$j<$firstDay;$j++,$counter++)
{
echo "<td> </td>"; // show days
}
$counter++; // first row counter correction
}
echo "<td>$i</td>";
if($counter%7==0)
{
echo "</tr><tr>";
}
}
echo "</tr>";