Select the last inserted row Every 1 second - php

I have 2 files:
1. chat.php: contain chat messages.
2. loadSingle.php: grab last new message every 1 second.
When I get the last message it was always return and get the last one. I want to get the last message without duplicate every time.
chat.php:
function loadlastmsg(){
var fromIdl = "<?php echo $chat_from_id;?>";
$.ajax({
type:'POST',
url:'loadSingle.php',
data:{fromIdl: fromIdl,},
cache: false,
beforeSend:function(data){
},
success: function(data)
{
$('#mainmsgs').append(data);
}
});
}
setInterval(function(){
loadlastmsg();
}, 1000);
</script>
Load Last Message
loadSingle.php:
<?php
if(isset($_POST["fromIdl"], $_POST["fromIdl"]))
{
$chat_from_ids = $_POST["fromIdl"];
require_once 'config/config.php';
mysqli_set_charset($conn,"utf8mb4");
$chinbox = array();
$result=$conn->query("SELECT * FROM chat WHERE id = (SELECT MAX(id) FROM chat WHERE to_id=$userId AND from_id=$chat_from_ids OR to_id=$chat_from_ids AND from_id=$userId) ORDER BY chat.send_date DESC LIMIT 1");
while ($chinbxsx = mysqli_fetch_assoc($result)) {
$chinbox[] = $chinbxsx;
$from_id = $chinbxsx['from_id'];
$subject = $chinbxsx['subject'];
$message = $chinbxsx['message'];
$get_date = $chinbxsx['send_date'];
$senddate = date_create($chinbxsx['send_date']);
$senddate = date_format($senddate, 'Y/m/d H:i:s');
$from_name = $chinbxsx['from_name'];
if($from_id != $userId){
$from_image = $chinbxsx['from_image'];
$msgclass = 'msgmRec';
}else{
$from_image = $userImage;
$msgclass = 'msgmSend';
}
// if($get_date > $get_date){
echo "<div class='msgm $msgclass'><img class='cmavsm' id='cmavsm' style='background-image: url($from_image);' /><p class='smRec'>$message</p><span class='date_span'>$senddate</span></div>";
// }
}
$conn->close();
}
?>
The mistake is: get the last message every 1 second. every time without stop it. I want to get the last message one time without loop the last message. thanks.

Using Ajax for chat will have poor performance always. You must consider using Web sockets.
See the below link for a sample
https://phppot.com/php/simple-php-chat-using-websocket/

I can't warranty this will be a fixed code, but it will give you the idea of how to discard a message on the client side if already received:
CLIENT SIDE:
<script>
/* Other code ... */
// Global variable for save the latest message ID.
var _latestMessageID = -1;
$(document).ready(function()
{
// Start getting messages...
setInterval(
function() {loadlastmsg();},
1000
);
});
function loadlastmsg()
{
var fromIdl = "<?php echo $chat_from_id;?>";
var formData = {fromIdl: fromIdl};
$.ajax({
type:'POST',
url:'loadSingle.php',
data: $.param(formData),
cache: false,
success: function(data)
{
if (data && data["ID"] > _latestMessageID)
{
$('#mainmsgs').append(data["message"]);
_latestMessageID = data["ID"];
}
}
});
}
</script>
SERVER SIDE:
<?php
require_once 'config/config.php';
if(isset($_POST["fromIdl"]) && $_POST["fromIdl"])
{
$chat_from_ids = $_POST["fromIdl"];
mysqli_set_charset($conn,"utf8mb4");
$chinbox = array();
$result=$conn->query(
"SELECT *
FROM chat
WHERE id = (SELECT MAX(id)
FROM chat
WHERE (to_id=$userId AND from_id=$chat_from_ids)
OR (to_id=$chat_from_ids AND from_id=$userId))
ORDER BY chat.send_date DESC LIMIT 1"
);
// Since the query has LIMIT of 1 this should only loop one time.
while ($chinbxsx = mysqli_fetch_assoc($result))
{
$chinbox[] = $chinbxsx;
$from_id = $chinbxsx['from_id'];
$subject = $chinbxsx['subject'];
$message = $chinbxsx['message'];
$get_date = $chinbxsx['send_date'];
$senddate = date_create($chinbxsx['send_date']);
$senddate = date_format($senddate, 'Y/m/d H:i:s');
$from_name = $chinbxsx['from_name'];
if ($from_id != $userId)
{
$from_image = $chinbxsx['from_image'];
$msgclass = 'msgmRec';
}
else
{
$from_image = $userImage;
$msgclass = 'msgmSend';
}
$msgID = $chinbxsx['id'];
}
$returnArray = array();
$returnArray["ID"] = $msgID;
$returnArray["message"] = "<div class='msgm $msgclass'><img class='cmavsm' id='cmavsm' style='background-image: url($from_image);' /><p class='smRec'>$message</p><span class='date_span'>$senddate</span></div>";
echo json_encode($result);
$conn->close();
}
?>

Related

e.preventDefault / return false breaks ajax script firing properly

I'm creating an ajax script to update a few fields in the database. I got it to a point where it worked but it sent the user to the php script instead of staying on the page so I did some googling, and people suggested using either return false; or e.preventDefault() however, if I do this, it breaks the php script on the other page and returns a fatal error. I might be missing something being newish to AJAX but it all looks right to me
JS:
$(document).ready(function() {
var form = $('form#edit_child_form'),
data = form.serializeArray();
data.push({'parent_id': $('input[name="parent_id"]').val()});
$('#submit_btn').on('click', function(e) {
e.preventDefault();
$.ajax({
url: form.prop('action'),
dataType: 'json',
type: 'post',
data: data,
success: function(data) {
if (data.success) {
window.opener.$.growlUI(data.msg);
}
},
error: function(data) {
if (!data.success) {
window.opener.$.growlUI(data.msg);
}
}
});
});
})
AJAX:
<?php
//mysql db vars here (removed on SO)
$descriptions = $_GET['descriptions'];
$child_id = $_GET['child_id'];
$parent_id = $_GET['parent_id'];
$get_child_ids = $dbi->query("SELECT child_ids FROM ids WHERE parent = ". $parent_id ." ORDER BY id"); //returns as object
$count = 0;
$res = array();
while ($child_row = $get_child_ids->fetch_row())
{
try
{
$dbi->query("UPDATE ids SET description = '$descriptions[$count]', child_id = '$child_id[$count]' WHERE parent_id = $child_row[0]");
$res['success'] = true;
$res['msg'] = 'Success! DDI(s) updated';
} catch (Exception $e) {
$res['success'] = true;
$res['msg'] = 'Error! '. $e->getMessage();
}
$count++;
}
echo json_encode($res);
it's probably something really small that I've just missed but not sure what - any ideas?
my solution:
I var_dumped $_GET and it returned null - changed to $_REQUEST and it got my data so all good :) thanks for suggestions
Try the following instead.
I moved the form data inside click and enclosed the mysql queries values in single quotes.
JS:
$(document).ready(function() {
var form = $('form#edit_child_form');
$('#submit_btn').on('click', function(e) {
e.preventDefault();
var data = form.serializeArray();
data.push({'parent_id': $('input[name="parent_id"]').val()});
$.ajax({
url: form.prop('action'),
dataType: 'json',
type: 'get',
data: data,
success: function(data) {
if (data.success) {
window.opener.$.growlUI(data.msg);
}
},
error: function(data) {
if (!data.success) {
window.opener.$.growlUI(data.msg);
}
}
});
});
})
AJAX:
<?php
//mysql db vars here (removed on SO)
$descriptions = $_GET['descriptions'];
$child_id = $_GET['child_id'];
$parent_id = $_GET['parent_id'];
$get_child_ids = $dbi->query("SELECT child_ids FROM ids WHERE parent = '". $parent_id ."' ORDER BY id"); //returns as object
$count = 0;
$res = array();
while ($child_row = $get_child_ids->fetch_row())
{
try
{
$dbi->query("UPDATE ids SET description = '$descriptions[$count]', child_id = '$child_id[$count]' WHERE parent_id = '$child_row[0]'");
$res['success'] = true;
$res['msg'] = 'Success! DDI(s) updated';
} catch (Exception $e) {
$res['success'] = true;
$res['msg'] = 'Error! '. $e->getMessage();
}
$count++;
}
echo json_encode($res);
You are using an AJAX POST request so in your PHP you should be using $_POST and not $_GET.
You can just change this:
$descriptions = $_GET['descriptions'];
$child_id = $_GET['child_id'];
$parent_id = $_GET['parent_id'];
to this:
$descriptions = $_POST['descriptions'];
$child_id = $_POST['child_id'];
$parent_id = $_POST['parent_id'];

Getting correct value of num_rows back AJAX/JSON

I have a notification system that out puts the right value of 1 and updates the div accordingly when a user posts one on my wall.
{
"num":1,
"notification_id":"640",
"notification_content":"Lucy Botham posted a status on your wall",
"notification_throughurl":"singlepoststreamitem.php?streamitem_id=515",
"notification_triggeredby":"85",
"notification_status":"1"
}
But if a user posts twice it does nothing and doesn't update at all.
{
"num":1,
"notification_id":"641",
"notification_content":"Lucy Botham posted a status on your wall",
"notification_throughurl":"singlepoststreamitem.php?streamitem_id=516",
"notification_triggeredby":"85",
"notification_status":"1"
}
{
"num":1,
"notification_id":"642",
"notification_content":"Lucy Botham posted a status on your wall",
"notification_throughurl":"singlepoststreamitem.php?streamitem_id=517",
"notification_triggeredby":"85",
"notification_status":"1"
}
CLIENT SIDE
$user1_id=mysqli_real_escape_string($mysqli,$_SESSION['id']);
$call="select MAX(notification_id) AS notification_id ,notification_status,notification_targetuser,notification_triggeredby,notification_throughurl from notifications WHERE notification_targetuser='$user1_id' AND notification_status='1'";
$chant=mysqli_query($mysqli,$call) or die(mysqli_error($mysqli));
while($notification=mysqli_fetch_array($chant)){
?>
<script type="text/javascript">
var notification_id="<?php echo $notification['notification_id']?>";
var notification_targetuser="<?php echo $notification['notification_targetuser']?>";
var notification_triggeredby="<?php echo $notification['notification_triggeredby']?>";
function loadIt() {
$.ajax({
type: "GET",
url: "viewajax.php?notification_id="+notification_id+"&notification_targetuser="+notification_targetuser+"&notification_triggeredby="+notification_triggeredby,
dataType:"json",
success: function(data){
if(data.notification_stream=1){
$("#notif_ui"+notification_id).prepend('<div class="notif_text"><div id="notif_actual_text-" class="notif_actual_text"><img border="1" src="userimages/cropped'+data['notification_triggeredby']+'.jpg" onerror=this.src="userimages/no_profile_img.jpeg" width="40" height="40" ><br />'+data['notification_content']+' <br />'+data['notification_time']+'<br/></div></div></div><hr/>');
i = parseInt($("#mes").text()); $("#mes").text((i+data.num));
if(!data.notification_id.length) {
//no results...
return;
}
notification_id = data.notification_id;
}
}
});
}
setInterval(loadIt, 10000);
</script>
<? } ?>
SERVER SIDE
$json = array();
$com=mysqli_query($mysqli,"SELECT * from notifications WHERE notification_targetuser='$idw' AND notification_triggeredby='$ide' AND notification_status='1' ORDER BY notification_id")or die($mysqli);
while($row = mysqli_fetch_assoc($com)){
$num = mysqli_num_rows($com);
if($num){
$json['num'] = 1;
}else{
$json['num'] = 0;
}
$json['notification_id'] = $row['notification_id'];
$json['notification_content'] = $row['notification_content'];
$json['notification_throughurl'] = $row['notification_throughurl'];
$json['notification_triggeredby'] = $row['notification_triggeredby'];
$json['notification_status'] = $row['notification_status'];
echo json_encode($json);
}}
$sql = "UPDATE notifications SET notification_status = '2' WHERE notification_targetuser='$idw'";
$go = mysqli_query($mysqli,$sql) or die(mysqli_error($mysqli));
You're echoing the JSON results inside a loop, so if the loop executes more than once, the final result is not valid JSON data. It's just multiple chunks of JSON.
while($row = mysqli_fetch_assoc($com)){
$id = $row['notification_id'];
$num = mysqli_num_rows($com);
if($num){
$json['num'] = 1;
}else{
$json['num'] = 0;
}
$json[$id]['notification_id'] = $row['notification_id'];
$json[$id]['notification_content'] = $row['notification_content'];
$json[$id]['notification_throughurl'] = $row['notification_throughurl'];
$json[$id]['notification_triggeredby'] = $row['notification_triggeredby'];
$json[$id]['notification_status'] = $row['notification_status'];
}
echo json_encode($json);
Then you'll need to adjust your Javascript to expect an array instead of a flat object.

phpexcel returns blank excel file using ajax

I have created a phpexcel script that prints reports in excel. The test code was ok but when I added some ajax for onclick event in a form, it returns blank excel file. This is my phpexcel code:
include($_SERVER['DOCUMENT_ROOT']."/excel/Classes/PHPExcel.php");
include($_SERVER['DOCUMENT_ROOT']."/excel/Classes/PHPExcel/Writer/Excel2007.php");
include($_SERVER['DOCUMENT_ROOT']."/excel/Classes/PHPExcel/IOFactory.php");
$dept = "";
$from = "";
$to = "";
set_time_limit(0);
$dept = $_POST['dept'];
$from = date("Y-m-d",strtotime($_POST['from']));
$to = date("Y-m-d",strtotime($_POST['to']));
try{
$query = $con->prepare("SELECT * FROM emptb WHERE Department = :dept ORDER BY id ASC");
$query->bindParam(':dept',$dept);
$query->execute();
}
catch(PDOException $e){
echo $e->getMessage();
exit();
}
$objPHPExcel = new PHPExcel;
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->setActiveSheetIndex(0);
//set default font
$objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->setName('Verdana');
//set titles
$objPHPExcel->getActiveSheet()->SetCellValue('B1','EMPLOYEE ATTENDANCE LOGS');
$objPHPExcel->getActiveSheet()->getPageSetUp()->setRowstoRepeatAtTopByStartAndEnd(1,3);
$objPHPExcel->getActiveSheet()->getRowDimension(1)->setRowHeight(29.25);
//merge cells
$objPHPExcel->getActiveSheet()->mergeCells('B1:T1');
$objPHPExcel->getActiveSheet()->mergeCells('C4:D4');
$objPHPExcel->getActiveSheet()->mergeCells('E8:F8');
//set text alignment
$objPHPExcel->getActiveSheet()->getStyle('B1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->setSize(18);
$objPHPExcel->getActiveSheet()->getStyle('B1')->getFill()->getStartColor()->setARGB('#333');
//set column width
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(6.14);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(0.67);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(10.86);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(1.43);
$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(9.71);
$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(1.43);
$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(10.7);
$objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(1.57);
$objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(2);
$objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(9);
$objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(0.58);
$objPHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth(0.92);
$objPHPExcel->getActiveSheet()->getColumnDimension('M')->setWidth(9);
$objPHPExcel->getActiveSheet()->getColumnDimension('N')->setWidth(1.71);
$objPHPExcel->getActiveSheet()->getColumnDimension('O')->setWidth(2.43);
$objPHPExcel->getActiveSheet()->getColumnDimension('P')->setWidth(6.14);
$objPHPExcel->getActiveSheet()->getColumnDimension('Q')->setWidth(1.71);
$objPHPExcel->getActiveSheet()->getColumnDimension('R')->setWidth(9.29);
$objPHPExcel->getActiveSheet()->getColumnDimension('S')->setWidth(4);
$objPHPExcel->getActiveSheet()->getColumnDimension('T')->setWidth(0.67);
$objPHPExcel->getActiveSheet()->getColumnDimension('U')->setWidth(0.67);
$rowCount = 4;
while($row = $query->fetch())
{
$rowTitle = $rowCount + 2;
$rowTitle1 = $rowCount + 4;
//data label
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowCount)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->mergeCells('C'.($rowCount).':D'.($rowCount));
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowCount)->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowCount)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowCount)->getFont()->setSize(12);
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowCount)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowCount,'ID No:');
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowTitle)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->mergeCells('C'.($rowTitle).':D'.($rowTitle));
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowTitle)->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowTitle)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowTitle)->getFont()->setSize(12);
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowTitle)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowTitle,'Name:');
$objPHPExcel->getActiveSheet()->getStyle('I'.$rowCount)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->mergeCells('I'.($rowCount).':J'.($rowCount));
$objPHPExcel->getActiveSheet()->getStyle('I'.$rowCount)->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('I'.$rowCount)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('I'.$rowCount)->getFont()->setSize(12);
$objPHPExcel->getActiveSheet()->getStyle('I'.$rowCount)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('I'.$rowCount,'Dept:');
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowTitle1)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->mergeCells('C'.($rowTitle1).':D'.($rowTitle1));
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowTitle1)->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowTitle1)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowTitle1)->getFont()->setSize(12);
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowTitle1)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowTitle1,'Section:');
$objPHPExcel->getActiveSheet()->getStyle('I'.$rowTitle1)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->mergeCells('I'.($rowTitle1).':J'.($rowTitle1));
$objPHPExcel->getActiveSheet()->getStyle('I'.$rowTitle1)->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('I'.$rowTitle1)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('I'.$rowTitle1)->getFont()->setSize(12);
$objPHPExcel->getActiveSheet()->getStyle('I'.$rowTitle1)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('I'.$rowTitle1,'Line:');
//data contents
$objPHPExcel->getActiveSheet()->mergeCells('E'.($rowCount).':G'.($rowCount));
$objPHPExcel->getActiveSheet()->getStyle('E'.$rowCount)->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->SetCellValue('E'.$rowCount,$row['EmpID']);
$objPHPExcel->getActiveSheet()->getStyle('E'.$rowCount)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('E'.$rowCount)->getFont()->setSize(12);
$objPHPExcel->getActiveSheet()->getStyle('E'.$rowCount)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->mergeCells('E'.($rowTitle).':S'.($rowTitle));
$objPHPExcel->getActiveSheet()->SetCellValue('E'.$rowTitle,$row['Lastname'] . ', ' . $row['Firstname']);
$objPHPExcel->getActiveSheet()->getStyle('E'.$rowTitle)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('E'.$rowTitle)->getFont()->setSize(12);
$objPHPExcel->getActiveSheet()->getStyle('E'.$rowTitle)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->mergeCells('L'.($rowCount).':S'.($rowCount));
$objPHPExcel->getActiveSheet()->SetCellValue('L'.$rowCount,$row['Department']);
$objPHPExcel->getActiveSheet()->getStyle('L'.$rowCount)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('L'.$rowCount)->getFont()->setSize(12);
$objPHPExcel->getActiveSheet()->getStyle('L'.$rowCount)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('E'.$rowTitle1,$row['SectionName']);
$objPHPExcel->getActiveSheet()->getStyle('E'.$rowTitle1)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('E'.$rowTitle1)->getFont()->setSize(12);
$objPHPExcel->getActiveSheet()->getStyle('E'.$rowTitle1)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('L'.$rowTitle1,$row['LineName']);
$objPHPExcel->getActiveSheet()->getStyle('L'.$rowTitle1)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('L'.$rowTitle1)->getFont()->setSize(12);
$objPHPExcel->getActiveSheet()->getStyle('L'.$rowTitle1)->getFont()->setName('Arial');
$rowCount++;
try{
$subquery = $con->prepare("SELECT c.dt,a.TimeIn,a.LunchOut,a.LunchIn,a.RNDOUT FROM cal c LEFT JOIN attendance a ON a.ValidDate = c.dt
AND a.EmpID = :id WHERE c.dt BETWEEN DATE('2015-08-01') AND DATE('2015-08-30') GROUP BY c.dt ORDER BY c.dt ASC");
$subquery->bindParam(':id',$row['EmpID']);
$subquery->execute();
}
catch(PDOException $e){
echo $e->getMessage();
exit();
}
$titleRow = $rowCount + 5;
$rowCount += 6;
while($subrow = $subquery->fetch())
{
if($subrow['TimeIn'] == "00:00:00")
{
$TimeIn = "";
}
else
{
$TimeIn = $subrow['TimeIn'];
}
if($subrow['LunchOut']=="00:00:00")
{
$LunchOut = "";
}
else
{
$LunchOut = $subrow['LunchOut'];
}
if($subrow['LunchIn']=="00:00:00")
{
$LunchIn = "";
}
else
{
$LunchIn = $subrow['LunchIn'];
}
if($subrow['RNDOUT']=="00:00:00")
{
$TimeOut = "";
}
else
{
$TimeOut = $subrow['RNDOUT'];
}
$objPHPExcel->getActiveSheet()->getStyle('C'.$titleRow)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->getStyle('C'.$titleRow)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('C'.$titleRow)->getFont()->setSize(11);
$objPHPExcel->getActiveSheet()->getStyle('C'.$titleRow)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('C'.$titleRow,'Date');
$objPHPExcel->getActiveSheet()->getStyle('E'.$titleRow)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->getStyle('E'.$titleRow)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('E'.$titleRow)->getFont()->setSize(11);
$objPHPExcel->getActiveSheet()->getStyle('E'.$titleRow)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('E'.$titleRow,'TimeIn');
$objPHPExcel->getActiveSheet()->getStyle('G'.$titleRow)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->mergeCells('G'.($titleRow).':H'.($titleRow));
$objPHPExcel->getActiveSheet()->getStyle('G'.$titleRow)->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('G'.$titleRow)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('G'.$titleRow)->getFont()->setSize(11);
$objPHPExcel->getActiveSheet()->getStyle('G'.$titleRow)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('G'.$titleRow,'LunchOut');
$objPHPExcel->getActiveSheet()->getStyle('J'.$titleRow)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->getStyle('J'.$titleRow)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('J'.$titleRow)->getFont()->setSize(11);
$objPHPExcel->getActiveSheet()->getStyle('J'.$titleRow)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('J'.$titleRow,'LunchIn');
$objPHPExcel->getActiveSheet()->getStyle('M'.$titleRow)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->getStyle('M'.$titleRow)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('M'.$titleRow)->getFont()->setSize(11);
$objPHPExcel->getActiveSheet()->getStyle('M'.$titleRow)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('M'.$titleRow,'TimeOut');
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowCount)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowCount)->getFont()->setSize(10);
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowCount)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowCount,$subrow['dt']);
$objPHPExcel->getActiveSheet()->getStyle('E'.$rowCount)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->getStyle('E'.$rowCount)->getFont()->setSize(10);
$objPHPExcel->getActiveSheet()->getStyle('E'.$rowCount)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('E'.$rowCount,$TimeIn);
$objPHPExcel->getActiveSheet()->getStyle('G'.$rowCount)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->getStyle('G'.$rowCount)->getFont()->setSize(10);
$objPHPExcel->getActiveSheet()->getStyle('G'.$rowCount)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('G'.$rowCount,$LunchOut);
$objPHPExcel->getActiveSheet()->getStyle('J'.$rowCount)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->getStyle('J'.$rowCount)->getFont()->setSize(10);
$objPHPExcel->getActiveSheet()->getStyle('J'.$rowCount)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('J'.$rowCount,$LunchIn);
$objPHPExcel->getActiveSheet()->getStyle('M'.$rowCount)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->getStyle('M'.$rowCount)->getFont()->setSize(10);
$objPHPExcel->getActiveSheet()->getStyle('M'.$rowCount)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('M'.$rowCount,$TimeOut);
$rowCount++;
}
$rowCount+=1;
$newRow = $objPHPExcel->getActiveSheet()->getHighestRow();
$objPHPExcel->getActiveSheet()->setBreak('A'.$newRow,PHPExcel_WorkSheet::BREAK_ROW);
}
$excelWriter = PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel2007');
header('Content-Type:application/ms-excel');
header('Content-Disposition:attachment;filename="'.$dept.'.xlsx"');
header('Cache-Control:max-age=0');
$excelWriter->save('php://output');
And here is my ajax function that somehow returns empty value
function myFunction()
{
var idept = $("#cmbdept[name=dept]").val();
var first = $("#from[name=from]").val();
var second = $("#to[name=to]").val();
$.ajax({
url: "printreport.php",
type: 'post',
data: {dept: idept,from: first,to: second},
cache: false,
global: false;
success: function(data)
{
//alert('Report is printing');
window.open('http://localhost/hrtms/printreport.php','_blank');
}
});
return false;
}
I think you called printreport.php twice.
in first call (in ajax), that make excel file.
in second call (in window.open), that has no parameters.
that's why return empty file, I guess.
How about make real file in printreport.php, and window.open created file's web path?
this is my code when i was make excel file through phpexcel.
$objWriter = PHPExcel_IOFactory::createWriter($xlsObj, 'Excel2007');
$filename = 'FILENAME_WHAT_YOU_WANT';
$file_full_name = 'DATA_PATH_WHAT_YOU_WANT' . '/' . $filename;
$objWriter->save($file_full_name);
P.S i'm not good at English, if you feel weird, please forgive me.
-----appended for more-----
in PHP for return file path after create excel file
if(file_exists($file_full_name)){
echo json_encode(array('error'=>false, 'export_path'=>'/temp_upload/' . $filename));
}else{
echo json_encode(array('error'=>true, 'error_msg' => 'Export Failed'));
}
in javascript for link to created excel file
$.ajax({
'url': '/menu/audience/exportActivity',
'dataType': 'json',
'type': 'post',
'data': data,
success: function(r){
//for loading animation to hide
$('body').find('div.loading.all').css('display', 'none');
if(!r.error){
location.href = r.export_path;
}
},
error: function(a, b, c){
$('body').find('div.loading.all').css('display', 'none');
}
});
that's my code when i coded

PHP/Jquery auto check data then do insert

For example, I have the following data
Name Date
Aplha 10/05/1988
Bravo 10/04/1999
Charlie 10/08/1990
I'm trying to make a auto check data (database) for every minute,
and compare it with the current Date on the computer, if its the same, I can insert message like happy birthday.
Someone can provide reference or solution to this, would be appreciated.
its like notification but in this case it will send message automatic
edited note - nvm i got it..updated script
my js
$(function()
{
setInterval(function() {
$.ajax({
url: "dooBday.php",
success: function (data) {
$("#feedback").html(data);
}
});
}, 1000 * 60);
});
my dooBday function
$tgl=date("d/m");
$tglInt=date("d/m");
$tglInt=preg_replace( '~\D~', '', $tglInt);
$tglInt=intval($tglInt);
// Database Object
$tablename = "Phonebook_New";
$tablename2 = "USER_ID";
$xo=0;
$xx=0;
$VinDB = new VinDB();
// Get Data
$query2 = "SELECT * FROM ".$tablename2." WHERE UserID='".getMultiUserID()."'";
$result2 = $VinDB->query($query2);
if ($VinDB->num_rows($result2) != 0)
{
$line2 = $VinDB->fetch_array($result2);
if($line2["bdaySts"]==1 and strlen(trim($line2["bdayMsg"])) > 0){
// Get Data--------------------------------
$query = "SELECT * FROM ".$tablename." WHERE User_ID='".getMultiUserID()."' AND bdaySent='x'";
$result = $VinDB->query($query);
if ($VinDB->num_rows($result) != 0)
{
while ($line = $VinDB->fetch_array($result))
{
if(!empty($line["Ultah"])){
$tglNew=substr($line["Ultah"], 0, -5);
if($tgl==$tglNew){
$datex = date('Y/m/d');
$timex = date('H:i:s');
$schedule= date($datex . '-' . $timex);
//doo Update Contact Sent--------------------
$sqlquery[$xo]="UPDATE ".$tablename." SET bdaySent='Sent' where User_ID='".getMultiUserID()."' and nomor='".$line["nomor"]."'";
$xo++;
// doo Send Message----------------------------
$inuquery[$xx] = "INSERT INTO Schedule ";
$inuquery[$xx] .= "(message,phone_number,Schedule,Status,User_ID) ";
$inuquery[$xx] .= "VALUES ('".$line2['bdayMsg']."','".$line['PhoneNumber']."','".$schedule."','Processing','";
if (isset($_SESSION['user_id2']))
{
$inuquery[$xx] .= $_SESSION['user_id2']."')";
} else {
$inuquery[$xx] .= "Unknown')";
}
$xx++;
}}
}//end while
}// end if
}
}//end send bday
for($i=0;$i<$xo;$i++){
$result = $VinDB->query($sqlquery[$i]);
$result2 = $VinDB->query($inuquery[$i]);
}
I think you want to wish users. If I am right. You can do it like this.
put this code on your page where you would like to check every minute
setInterval(function() {
$.ajax({
url: "ajx.php",
success: function (data) {
$("#feedback").html(data);
}
});
}, 1000 * 60);
And this will be your ajax.php file
<?php
// Name Date
// Aplha 10/05/1988
// Bravo 10/04/1999
// Charlie 10/08/1990
$alphaDob = '02/04/1988';
$exp = explode('/', $alphaDob);
$userDate = $exp[0];
$userMonth = $exp[1];
$currentDate = date('Y-m-d');
$exp = explode('-', $currentDate);
$currentDate = $exp[2];
$currentMonth = $exp[1];
if($currentMonth == $userMonth && $currentDate == $userDate) {
echo 'Happy Birthday';
}
For good performance use Ajax-Long-Polling function, example can be found here Long-Polling Example

php jquery straight url

Hello, I have some questions about how to protect this script from a straight url?
Members can just can go 'pages/map/hospital.php?status=healed' and voila, they don't need any wait time. How do I fix this?!
<?php
$status = $_GET['status'];
if(isset($status)){
session_start();
include('../../includes/core/member.php');
include('../../includes/core/config.php');
$member_id = $_SESSION['member_id'];
if($status == 'healed'){
mysql_query("UPDATE `members` SET `now_health` = '".$m_max_health."' WHERE `member_id` = '".$member_id."'");
}
}else{
include('includes/core/member.php');
}
$health = $m_max_health - $m_now_health;
$wait_time = $health * 5;
?>
<p id='health'>Healing (<?=$wait_time?>)</p>
<script>
$('#health').one('click', function() {
var count = <?=$wait_time?>;
countdown = setInterval(function(){
$("p#health").html(count + " seconds remaining!");
if (count == 0) {
$.ajax({
url: 'pages/map/hospital.php?status=healed',
success: function(data) {
clearInterval(countdown);
$("p#health").html('you have healed');
}
});
}
count--;
}, 1000);
});
</script>
Server-side validation is required.
I see that you already have the initial $wait_time in a variable. So you would want to leverage this and perform some basic math using a datetime function to ensure the count <= 0.

Categories