phpexcel returns blank excel file using ajax - php

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

Related

Select the last inserted row Every 1 second

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();
}
?>

saving data from csv to php and mysql

I am trying to import all the data from csv to the database.
Below code is ajax request that is sent to a php file.
$('#upload_location_csv').click(function(e){
e.preventDefault();
var queryDict = {};
location.search.substr(1).split("&").forEach(function(item) {queryDict[item.split("=")[0]] = item.split("=")[1]});
fi = document.getElementById("csv_file_input").files[0];
reader = new FileReader;
reader.onload = function(){
csv_data = reader.result;
$.ajax({
type:"post",
url:ajax_root_path+'fend.php',
data:{
location_id:queryDict['id'],
csv_data:csv_data,
perform_action:"save_delivery_csv_data"
},
success:function(resObj){
window.location.reload();
},
error:function(resObj){
}
});
};
reader.readAsText(fi);
});
This is the action that is performed, where here is, save_delivery_csv_data .
When I click on import csv, the page reloads and no request is sent to fend.php.
case 'save_delivery_csv_data':
{
$location_id = $param_array['location_id'];
$csv_data = $param_array['csv_data'];
$csv_data_rows = explode("\n",$csv_data);
unset($csv_data_rows[0]);
$csv_data_rows = array_values($csv_data_rows);
debug($csv_data_rows);
$csv_data_array = array();
foreach ($csv_data_rows as $csv_row_key => $csv_row_value)
{
$csv_row_value_array = explode(",",$csv_row_value);
debug($csv_row_value_array);
if(count($csv_row_value_array) == 5)
{
/*$csv_data_array[$csv_row_key] = array();
$csv_data_array[$csv_row_key]['locality_id'] = $csv_row_value_array[0];
$csv_data_array[$csv_row_key]['locality_name'] = $csv_row_value_array[1];
$csv_data_array[$csv_row_key]['minimum_order_amount'] = $csv_row_value_array[2];
$csv_data_array[$csv_row_key]['delivery_time'] = $csv_row_value_array[3];
$csv_data_array[$csv_row_key]['delivery_charge'] = $csv_row_value_array[4];*/
//debug($csv_row_value_array);
if(isset_empty($csv_row_value_array[3]))
{
//debug($csv_row_value_array);
$locality_id = $csv_row_value_array[0];
$location_outletValues = array();
$location_outletValues['cloud_site_id'] = $cloud_site_id;
$location_outletValues['location_id'] = $location_id;
$location_outletValues['locality_id'] = $locality_id;
$location_outletValues['minimum_order'] = $csv_row_value_array[2];
$location_outletValues['delivery_time'] = $csv_row_value_array[3];
$location_outletValues['delivery_charge'] = $csv_row_value_array[4];
$sql = "SELECT outlet_locality_id FROM ".PLATFORM_OUTLET_LOCALITIES."
WHERE location_id='".$location_id."' AND locality_id='".$locality_id."'";
$outlet_locality_array = $DB->query($sql);
//debug($outlet_locality_array);
if(count($outlet_locality_array) > 0)
{
$condition_array = array();
$condition_array['outlet_locality_id'] = $outlet_locality_array[0]->outlet_locality_id;
//debug($condition_array);
debug($location_outletValues);
$DB->update(PLATFORM_OUTLET_LOCALITIES,$location_outletValues,$condition_array);
}
else
{
$DB->insert(PLATFORM_OUTLET_LOCALITIES,$location_outletValues);
}
}
}
}
break;
//debug($csv_data_array);
}
What am I missing out here?? I also tried debugging variables values, but no request was sent to fend.php, whereas other request on the same page are being successfully sent.

Ajax requests out of memory

So I am working on this project where I have to make a photo sharing site, I select the photos and then upload them, send the link via email, and then the person goes on the link and downloads the photos. Everything works great when I have few photos and when not exceeding 100MB of data, when I go beyond that everything becomes unstable.
First of I am using HTML5's FileReader().The logic is the following:
I use FileReader() to transform each photo into a base64 code and every 3 photos transformed I send a 3 photos long base64 string via Ajax to a php file which then transforms the code into photos and uploads them into a folder on the server.
If I have 300 photos selected I do 100 ajax requests.
The first problem if if I exceed ~150MB of data ajax will give me an uncaught exception out of memory error.
The second problem is if I chose over 20-30 files the brower some times gets unresponsive even crashes..
Any suggestions what can I do ? Maybe the whole idea is wrong and I should start somewhere else, please help.
This is the code:
//Forming the inputs
$(document).on("change","#fileUp",function(e){
var file = null;
var files = e.target.files; //FileList object
var picReader = new FileReader();
$(".eventPop").html("");
$(".howMany").html("");
$(".eventPop").show();
$(".eventPop").append('<div class="adding"><img src="../public/cuts/uploading.gif" width="60px"></div>');
countUp = parseInt(countUp) + parseInt(files.length);
for(var i=0; i<=files.length-1; i++){
file = files[i];
var str = file.name.split(".")[0];
//
//var picReader = new FileReader();
if (file.type == "image/jpeg" || file.type == "image/png")
{
picReader.addEventListener("load",function(event){
count++;
var picFile = event.target;
$(".photos").append("<input type='hidden' id='ph"+count+"' get='"+picFile.result+"' /> ");
});
}
else
{
countUp--;
}
picReader.readAsDataURL(file);
}
});
//actual ajax requests
$(document).on('click','.uploadImages',function(){
info[1] = "4hold"+1 + Math.floor(Math.random() * 999999)+"_"+(new Date).getTime();
$.ajax({
type: "POST",
url: "index/loadIntoDB",
dataType:"text",
data: {info: info},
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function(result){
}
});
if (nrConfig > count)
{
nrConfig = count;
}
$(".eventPop").show();
$(".eventPop").html("");
$(".eventPop").append('<div class="adding"><p>Uploading files...'+( (nrConfig/count) * 100).toFixed(0)+'%</p></div>');
for(var i=1; i<=parseInt(nrConfig)+1; i++)
{
if (i == parseInt(nrConfig)+1)
{
info[2] = info[2].substring(2, info[2].length);
uploadImages(nrConfig,1);
}
else
{
//info[0] = i+"-"+info[0];
info[2] = info[2]+"--"+$("#ph"+i+"").attr("get");
}
}
});
function uploadImages(i,d){
info['3'] = i;
info['4'] = d;
$.ajax({
type: "POST",
url: "index/receiveImages",
dataType:"json",
data: {info : info },
beforeSend : function (){
//
},
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function(result){
for(index=result['leftOff']['1']; index <= result['info']['4']-1; index++)
{
if (result[index]['filesize'] < 1000000)
{
result[index]['filesize'] = Math.floor(result[index]['filesize']/1000)+"kb";
$("#ph"+result[index]['id']).append("<div class='filesize'>"+result[index]['filesize']+"</div>");
}
else
{
result[index]['filesize'] = (result[index]['filesize']/1000000).toFixed(2)+"MB";
$("#ph"+result[index]['id']).append("<div class='filesize'>"+result[index]['filesize']+"</div>");
}
if (result[index]['filesize'].length > 0)
{
$("#ph"+result[index]['id']+" .uploading").remove();
$("#ph"+result[index]['id']).append("<img src='layout/cuts/check.png' title='Uploaded' class='done'>");
$("#ph"+result[index]['id']+" .upd").remove();
}
}
$(".eventPop").html("");
$(".eventPop").append('<div class="adding"><p>Uploading files...'+( (result['info'][4]-1)/count * 100).toFixed(0)+'%</p></div>');
if (((result['info'][4]-1)/count * 100).toFixed(0) == 100)
{
setTimeout(function(){
$("progress").remove();
$(".eventPop").html("");
$(".eventPop").append("<div class='adding'>Upload complete!</div>");
setTimeout(function(){
$(".eventPop").html("");
$(".eventPop").append("<div class='adding'><div class='sendPhotos'><form action='#' onsubmit='return false;' method='post' enctype='multipart/form-data'><label>Your email</label><input type='text' class='yemail'/><br/><label>Friend's email</label><input type='text' class='fremail'/><br/><span class='tip'><div class='triangle'></div>You can send photos to multiple friends by typing their e-mail separated by ';'.<br/>Eg. 'thomas#gmail.com ; peter#gmail.com'</span><input type='submit' name='send' class='send' value='Send'></form></div></div>");
},1000);
},1000);
}
if (info[2].length)
{
info[2] = "";
}
if ( (parseInt(result['info']['4'])+parseInt(nrConfig)) >= count )
{
nrConfig = count-result['info']['4']+1;
}
if(result['info']['4'] <= count)
{
for(i=result['info']['4']; i <= parseInt(result['info']['4'])+parseInt(nrConfig); i++)
{
if (i == parseInt(result['info']['4'])+parseInt(nrConfig))
{
info[2] = info[2].substring(2, info[2].length);
uploadImages(nrConfig,result['info']['4']);
}
else
{
info[2] = info[2]+"--"+$("#ph"+i+"").attr("get");
}
}
}
}
});
}
PHP code:
public function receiveImages()
{
$string = strtok($_POST['info'][2],"--");
$currentID = $_POST['info']['4'];
$newArray['info']['3'] = $_POST['info']['3'];
$newArray['leftOff']['1'] = $currentID;
$phAdded = 0;
while($string != false && $phAdded < $_POST['info']['3'])
{
$newArray[$currentID]['id'] = $currentID;
$newArray[$currentID]['filesize'] = $this->saveImages($string,$_POST['info']['1'],$currentID);
$currentID++;
$phAdded++;
$string = strtok("--");
}
$newArray['info']['4'] = $currentID;
echo json_encode($newArray);
}
public function saveImages($base64img = "",$folder = "",$currentID = "")
{
$newArray = array();
if (!is_dir(UPLOAD_DIR.$folder))
{
mkdir(UPLOAD_DIR.$folder,0777);
}
$dir = UPLOAD_DIR.$folder."/";
if (strstr($base64img,'data:image/jpeg;base64,'))
{
$base64img = str_replace('data:image/jpeg;base64,', '', $base64img);
$uniqid = uniqid();
$file = $dir . $uniqid . '.jpg';
$file_name = $uniqid.".jpg";
}
else
{
$base64img = str_replace('data:image/png;base64,', '', $base64img);
$uniqid = uniqid();
$file = $dir . $uniqid . '.png';
$file_name = $uniqid.".png";
}
$data = base64_decode($base64img);
file_put_contents($file, $data);
$size = filesize($file);
if ($size > 1000000)
{
$size = number_format(($size/1000000),2)."MB";
}
else
{
$size = number_format(($size/1000),0)."kb";
}
return filesize($file);
}

How to run 2 PHP script simultaniously (non-blocking) for monitoring a popen command?

How to run 2 PHP script simultaniously (synchronous) for monitoring a popen command?
I have a script launching a command like this:
7za a -t7z -mx9 backup.7z "H:\Informatique\*"
And I would like to display the progress of the compression on a page using jQuery and PHP.
The php script running this command look like this:
if( ($fp = popen("7za a -t7z ".$GLOBALS["backup_compression"]." \"".$backuplocation.$backupname."\" \"".$pathtobackup."\"", "r")) ) {
while( !feof($fp) ){
$fread = fread($fp, 256);
$line_array = preg_split('/\n/',$fread);
$num_lines = count($line_array);
$_SESSION['job'][$jobid]['currentfile'] = $_SESSION['job'][$jobid]['currentfile']+$num_lines;
$num_lines = 0;
flush();
}
pclose($fp);
}
jQuery call the 7za script then jquery call the listener (listener.php) each 1000ms. the listener.php page contain the following code:
session_start();
$jobid = $_GET['jobid'];
if(!isset($_SESSION['job'][$jobid])) { $arr = array("error"=>"Job not found"); echo json_encode($arr); exit(); };
$arr = array(
"curfile" => $_SESSION['job'][$jobid]['currentfile'],
"totalfiles" => $_SESSION['job'][$jobid]['totalfiles'],
);
echo json_encode($arr);
$jobid = null;
$arr = null;
exit();
After the jquery call is complete (with the listener and we got a response from the server) we display the information with something normal like: $("currentfile").text(data['curfile']);
The problem is that the listener is in an infinite loop waiting for the first script to complete... and that's not the job of the listener... It's listening at the end of everything... when you listen, it's to know what's happening. :P
Do you have any idea what's going on and how can I fix this problem?
Or maybe you can help me with a new approch to this problem?
As always, any suggestions will be welcome.
Thank you.
EDIT
jQuery script:
function backup_launch(jobid) {
x('jobid: '+jobid+' on state '+state);
x('Listener launched');
listen(jobid);
timeout = setTimeout("listen('"+jobid+"')", 500);
$.ajax({
url:'backup.manager.php?json&jobid='+jobid+'&state='+state,
dataType:'json',
success:function(data)
{
state = 3;
}
});
}
function listen(jobid) {
$.ajax({
url:'backup.listener.php?json&jobid='+jobid,
dataType:'json',
success:function(data)
{
var curfile = data['curfile'];
var totalfiles = data['totalfiles'];
var p = curfile * 100 / totalfiles;
x('File '+curfile+' out of '+totalfiles+' progress%: '+p);
timeout = setTimeout("listen('"+jobid+"')", 500);
}
});
}
EDIT 2
I found Gearman (http://gearman.org/) but I don't know at all how to implement this and it needs to be portable/standalone... I'll try to investigate that.
EDIT 3
Full code for the backup.manager.php page. The script is sending the response right aay, but do the job in the background.
The listen.php page still wait for the command to finish before returning any results.
$jobid = isset($_GET['jobid']) ? $_GET['jobid'] : 0;
//Make sure jobid is specified
if($jobid == 0) { return; }
header("Connection: close");
#ob_end_clean();
ignore_user_abort();
ob_start();
echo 'Launched in backgroud';
$size = ob_get_length();
header("Content-Length: ".$size);
ob_end_flush();
flush();
$_SESSION['job'][$jobid]['currentfile'] = 0;
// 3. When app appove backup,
// - Write infos to DB
// - Zip all files into 1 backup file
$datebackup = time();
$bckpstatus = 1; //In progress
$pathtobackup = $_SESSION['job'][$jobid]['path'];
/*
$query = "INSERT INTO backups (watchID, path, datebackup, checksum, sizeori, sizebackup, bckpcomplete)
VALUES ($watchID, '{$path}', '{$datebackup}', '', '{$files_totalsize}', '', '{$bckpstatus}')";
$sth = $db->prepare($query);
$db->beginTransaction();
$sth->execute();
$db->commit();
$sth->closeCursor();
*/
$backupname = $jobid.".".$GLOBALS["backup_ext"];
$backuplocation = "D:\\";
if( ($fp = popen("7za a -t7z ".$GLOBALS["backup_compression"]." \"".$backuplocation.$backupname."\" \"".$pathtobackup."\"", "r")) ) {
while( !feof($fp) ){
$fread = fread($fp, 256);
$line_array = preg_split('/\n/',$fread);
$num_lines = count($line_array);
$_SESSION['job'][$jobid]['currentfile'] = $_SESSION['job'][$jobid]['currentfile']+$num_lines;
$num_lines = 0;
sleep(1);
flush();
}
pclose($fp);
}
Jeremy,
A couple of months ago, I answered a similar question about running server-side batch jobs in a *NIX/PHP environment. If I understand correctly, your requirement is different but it's possible there might be something in the answer which will help.
Run a batch file from my website
EDIT
Here's a modified version of your client-side code. You will see that the main things I have changed are :
to move listen(jobid); inside backup_launch's success handler.
to add error handlers so you can observe errors.
Everything else is just a matter of programming style.
function backup_launch(jobid) {
x(['jobid: ' + jobid, 'on state', state].join(' '));
$.ajax({
url: 'backup.manager.php',
data: {
'json': 1,
'jobid': jobid,
'state': state
}
dataType: 'json',
success:function(data) {
state = 3;
x("Job started: " + jobid);
listen(jobid);
x("Listener launched: " + jobid);
},
error: function(jqXHR, textStatus, errorThrown) {
x(["backup.manager error", textStatus, errorThrown, jobid].join(": "));
}
});
}
function listen(jobid) {
$.ajax({
url: 'backup.listener.php',
data: {
'json': 1
'jobid': jobid
},
dataType: 'json',
success: function(data) {
var curfile = data.curfile;
var totalfiles = data.totalfiles;
var p = curfile * 100 / totalfiles;
x(['File', curfile, 'out of', totalfiles, 'progress%:', p].join(' '));
timeout = setTimeout(function() {
listen(jobid);
}, 500);
},
error: function(jqXHR, textStatus, errorThrown) {
x(["Listener error", textStatus, errorThrown, jobid].join(": "));
}
});
}
I've decided to call the command for each individual file.
It is going to be slower, but it is safer to manage with file cause errors and which files was properly inserted in the archive.
I'll try to find something faster is the direcotry to archive got 10 000 icons file for exemple. Maybe 5 files at a time instead of one file at a time.
This code was intended for testing purposes, the code is not optimized at all for production.
index.html jquery script:
var state = 0;
var jobid = '';
var timeout;
var jobfiles;
var jobpaths = [];
$(document).ready(function() {
$("button").click(function(e) {
e.preventDefault();
console.log('Sending');
var path = $("input").val();
x('state 1 getting info - infpb');
state = 1;
$.ajax({
url:'backup.manager.php?json&path='+encodeURI(path)+'&type=0&state='+state,
dataType:'json',
success:function(data)
{
jobid = data['stats']['jobid'];
jobfiles = data['stats']['totalfiles'];
var jobsize = data['stats']['totalsize'];
for(var i = 0, len = jobfiles; i < len; i++) {
jobpaths.push(data[i]['File']);
}
state = 2;
x('state 2 - infpb stop (Information retrieved, launch backup) '+jobfiles+' files with '+jobsize+' bytes');
backup_launch(jobid);
}
});
});
});
function x(x) {
$("#l").append(x+"<br>");
}
var curfileid = 0;
function backup_launch(jobid) {
x('jobid: '+jobid+' on state '+state);
$.ajax({
url:'backup.manager.php',
data: {
'json': 1,
'jobid': jobid,
'state': state,
'path': jobpaths[curfileid]
},
dataType:'json',
success:function(data)
{
if(curfileid < jobfiles) {
x((curfileid+1)+' / '+jobfiles);
curfileid++;
backup_launch(jobid);
}
},
error: function(jqXHR, textStatus, errorThrown) {
x(["backup.manager error", textStatus, errorThrown, jobid].join(": "));
}
});
}
function listen(jobid) {
$.ajax({
url:'backup.listener.php?json&jobid='+jobid,
dataType:'json',
success:function(data)
{
var curfile = data['curfile'];
var totalfiles = data['totalfiles'];
var p = curfile * 100 / totalfiles;
x('File '+curfile+' out of '+totalfiles+' progress%: '+p);
timeout = setTimeout("listen('"+jobid+"')", 500);
}
});
}
backup.manager.php
set_time_limit(0);
require('../functions.php');
session_start();
$keepCPUlow_lastlookup = time();
$keepCPUlow_mindelay = 60;
function keepCPUlow() {
global $keepCPUlow_lastlookup, $keepCPUlow_mindelay;
if((time() - $keepCPUlow_lastlookup) > $keepCPUlow_mindelay) {
$keepCPUlow_lastlookup = time();
getSysload(75, 1000); // Max %, wait time in ms
}
}
$state = isset($_GET['state']) ? $_GET['state'] : 0;
if($state == '1') {
//
$json = isset($_GET['json']) ? true : false;// Result should be in json format
$path = isset($_GET['path']) ? $_GET['path'] : ''; // Path of the file or folder to backup
$type = isset($_GET['type']) ? $_GET['type'] : ''; // Type - not very useful, for now
//0. Assign a jobid for this job, it will help retrieve realtime information about this task
$jobid = hash('md4', (time().uniqid().session_id()));
//Store the current status (0) job not started
$_SESSION['job'][$jobid]['status'] = 0; //Not started... yet
// 1. Retrive list of files and stats
$fileslist = array(); //Will contain the list of files
$files_totalsize = 0; // Total size of files
// Check if file or folder
if(is_dir($path)) {
//Path is a folder, get the list of files
$files = getFilelist($path);
foreach($files as $file) { //For each files
if(!is_dir($file['File'])) { //That is not a directory
$files_totalsize = $files_totalsize+$file['Filesize']; //Increment toal size
$cpumon = keepCPUlow(); //if($cpumon[1]) echo ">CPU BURN".$cpumon[0]."<";
}
}
$files_total = count($files); // Number of files
} else {
$files_totalsize = $files_totalsize+getFilesize($path);
$files_total = 1;
}
$files['stats'] = array("totalfiles"=>$files_total, "jobid"=>$jobid, "totalsize"=>$files_totalsize);
//Store infos in session
$_SESSION['job'][$jobid]['totalfiles'] = $files_total;
$_SESSION['job'][$jobid]['totalsize'] = $files_totalsize;
$_SESSION['job'][$jobid]['path'] = is_dir($path) ? $path.'\\*' : $path;
$_SESSION['job'][$jobid]['currentfile'] = 0;
$_SESSION['job'][$jobid]['currentfile_path'] = '';
$_SESSION['job'][$jobid]['bname'] = "SafeGuard_".$jobid.".".$GLOBALS["backup_ext"];
$_SESSION['job'][$jobid]['blocation'] = "D:\\";
// 2. return to app and wait for ready confirmation
if(isset($_GET['json'])) {
echo json_encode($files);
}
exit();
}
else if($state == '2') {
$jobid = isset($_GET['jobid']) ? $_GET['jobid'] : 0;
$_SESSION['job'][$jobid]['currentfile'] = 0;
// 3. When app appove backup,
// - Write infos to DB
// - Zip all files into 1 backup file
$datebackup = time();
$bckpstatus = 1; //In progress
//$pathtobackup = $_SESSION['job'][$jobid]['path'];
$pathtobackup = isset($_GET['path']) ? $_GET['path'] : "--";
$backupname = $_SESSION['job'][$jobid]['bname'];
$backuplocation = $_SESSION['job'][$jobid]['blocation'];
/*
$query = "INSERT INTO backups (watchID, path, datebackup, checksum, sizeori, sizebackup, bckpcomplete)
VALUES ($watchID, '{$path}', '{$datebackup}', '', '{$files_totalsize}', '', '{$bckpstatus}')";
$sth = $db->prepare($query);
$db->beginTransaction();
$sth->execute();
$db->commit();
$sth->closeCursor();
*/
if( ($fp = popen("7za a -t7z ".$GLOBALS["backup_compression"]." \"".$backuplocation.$backupname."\" \"".$pathtobackup."\"", "r")) ) {
while( !feof($fp) ){
fread($fp, 256);
$num_lines = 1;
$_SESSION['job'][$jobid]['currentfile'] = $_SESSION['job'][$jobid]['currentfile']+$num_lines;
$num_lines = 0;
flush();
echo '1';
}
pclose($fp);
}
}

passing a javascript variable to a php function and quoting it correctly

Im using Zend Framework ..in one of my phtml file's i have this code
<script>
function foobar(id,type){
var idarray = <?php AppNamespace_General::getparentids( ?>id, type<?php ) ?>; // here the id and type are from js
//the php function returns a json array to the js variable
......
location.href = baseurl +'/somepage/id/'+id;
}
How can i correctly pass the js elements to the php function
The php function(Already thought of doing it via ajax..its quite complex)
public static function getparentids($id, $type, $elmarray = '') {
if (empty($elmarray)) { //avoiding redeclaration of array
$elmarray = array();
}
switch (strtolower($type)) {
case 'group':
case 'product':
case 'specification':
$gp_handler = new PackAssist_Model_DbTable_Groups();
$q = "SELECT * FROM t_groups WHERE group_id = $id";
$sql = $gp_handler->getAdapter()->query($q);
break;
case 'part':
$pt_handler = new PackAssist_Model_DbTable_Parts();
$q = "SELECT * FROM t_parts WHERE part_id = $id";
$sql = $pt_handler->getAdapter()->query($q);
break;
}
$result = $sql->fetchAll();
$i = 0;
if (count($result) > 0) {
foreach ($result as $row) {
if (isset($row['group_parent_id']) && $row['group_parent_id'] != 0) {
if (in_array($row['group_id'], $elmarray)) {
$e = $row['group_parent_id'];
} else if ($row['group_parent_id'] != 0) {
$e = $row['group_id'];
}
} else if (isset($row['part_group_id'])) {
$e = $row['part_group_id'];
} else if ($row['group_parent_id'] == 0) {
break;
}
if (isset($e) && !empty($e)) {
array_push($elmarray, $e);
}
self::getparentids($e, 'group', $elmarray);
$i++;
}
} else {
array_push($elmarray, $id);
}
array_pop($elmarray); //removing the group of super parent group which we dont need
if ($i == 0) { // just encode the array only once
echo json_encode(array_reverse($elmarray));
}
}
If you use jQuery, you can do the following to execute the JSON request:
$.ajax({
type: 'GET',
url: '/path/to/script.php',
data: '{ id: '+id+', type: '+type+' }',
contentType: 'application/json',
dataType: 'json',
success: function(data) {
dataObject = JSON.parse(data);
// process data
},
error: function(e) {
console.log(e.message);
}
});
You can use your existing PHP code with this solution. The url you point to would just have to print the JSON result, as you are currently doing in getparentids().

Categories