Dropdown getting only two value from xml file - php

I Am trying to add data into a combo box named combo_assembly using Ajax..
The Function is:
function populate_combo_assembly(xmlindata) {
var xmldata = xmlindata.getElementsByTagName('Assemblies');
if(xmldata.length <= 0) {
alert("Data Unavailable");
return;
}
window.document.getElementById('combo_assembly').options.length = 0;
var firstOption = new Option('--Please select--', '', false, false);
window.document.getElementById('combo_assembly').options.add(firstOption);
for(var i =0; i <= xmldata.length; i++) {
var typename = '';
var x,y;
x = xmlindata.getElementsByTagName('name')[i];
y = x.childNodes[0];
typename = y.nodeValue;
var newOption = new Option(typename, typename, false, false);
window.document.getElementById('combo_assembly').options.add(newOption);
}
window.document.getElementById('combo_assembly').disabled = false;
}
And taking The values from a file..Code is:
<?php
include("database/dbconfig.inc.php");
header("Content-type: text/xml");
echo "<?xml version=\"1.0\" ?>\n";
echo "<Assemblies>\n";
$select = "SELECT * FROM assembly";
try {
foreach($dbh->query($select) as $row) {
echo "<Assembly>\n<name>".$row['name']."</name>\n<id>".$row['id']."</id>\n<category>".$row['category']."</category>\n</Assembly>\n";
}
}
catch(PDOException $e) {
echo $e->getMessage();
die();
}
echo "</Assemblies>";
?>
THe problem is that this xml file is taking all the contents I from the database table. But the function is taking only the first two values from the xml code.
The Output of xml file
<Assemblies>
<Assembly>
<name>total</name>
<id>A00000</id>
<category>Brake</category>
</Assembly>
<Assembly>
<name>asd</name>
<id>A00001</id>
<category>Brake</category>
</Assembly>
<Assembly>
<name>ga</name>
<id>ga</id>
<category>Suspension</category>
</Assembly>
<Assembly>
<name>65</name>
<id>r00</id>
<category>Brake</category>
</Assembly>
<Assembly>
<name>yty</name>
<id>tyt</id>
<category>Suspension</category>
</Assembly>
<Assembly>
<name>Gaurav</name>
<id>Z0012</id>
<category>Brake</category>
</Assembly>
</Assemblies>
Thanks In advance for help.

You are retrieving the xmldata as
var xmldata = xmlindata.getElementsByTagName('Assemblies');
Shouldn't that be
var xmldata = xmlindata.getElementsByTagName('Assembly');
As the information is not contained in the wrapper element .

Related

Trying to receive json from php with ajax and print results in HTML

I'm trying to make a application using phonegap. I am trying to make a select using php return the result to ajax function and print the result...but I don't know if I am doing right and what I need to put in my html code to show the result.
AJAX CODE:
$(document).ready(function() {
$.ajax({
url : 'http://ip/again/www/index.php',
dataType : "json",
success : function(data){
var html = "";
for($i=0; $i < data.length; $i++){
html += "<strong>Nome:</strong> "+data[$i].nome +" "+
data[$i].sobreNome;
html += " <strong>Cidade:</strong> "+data[$i].cidade;
html += "<br />";
}
$('body').html(html);
}
});
});
</script>
PHP CODE:
<?php
$hostname = 'localhost';
$username = 'root';
$password = 'pass';
$database = 'mydb';
try {
$pdo = new PDO("mysql:host=$hostname;dbname=$database", $username,
$password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
//echo 'Conexao efetuada com sucesso!';
}
catch(PDOException $e)
{
echo $e->getMessage();
}
$sql = 'SELECT * FROM incidente ORDER BY codigo' ;
try {
$recebeConexao = $pdo->prepare($sql);
$recebeConexao->execute();
$result = $recebeConexao->fetchAll();
if ( count($result) ) {
foreach($result as $row) {
$incid=$row;
echo (json_encode($incid));
}
} else {
$incid=0;
}
} catch (PDOException $ex) {
echo "Erro no Banco";
}
?>
You're writing the for loop incorrectly. You must declare your variable with the var keyword like so:
for(var $i = 0; $i < data.length; $i++) {
// ...
}
Since your script does not return an array, the length property will not be available.
When you're dealing with an object in Javascript, you will want to use the for...in syntax (making sure to validate that the property belongs to the object you're iterating over).
However, the code you provided will not return an object or an array, because the JSON is malformed.
The correct way for an API to return multiple, unordered Javascript objects would be to wrap them in an array, like so:
if(count($result)) {
$list = array();
foreach($result as $row) {
$list[] = $row;
}
echo json_encode($list);
}
$.ajax({
// ...
success: function (data) {
// Loop over each object, since your script should ideally return an array
for (var $i = 0; $i < data.length; $i++) {
var object = data[$i];
html += '<strong>Nome:</strong> ' + object.nome + ' ' + object.sobreNome;
// etc...
}
}
});

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

Convert data to Json in CodeIgniter with AJAX

I am struggling to convert json code in CodeIgniter, i wanna make pagination.
I am using ajax and want to controle data convert to json and send it to view. I can someone explain me how to do that.
Code in controler, instead foreach part i am trying to make Json, and send it to view
function ajax(){
$rpp= $_POST['rpp'];
$last = $_POST['last'];
$pn = $_POST['pn'];
if($pn<1){
$pn=1;
}
elseif($pn>$last){
$pn =$last;
}
$l = ($pn - 1) * $rpp;
$this->db->limit($l, $rpp);
$row = $this->db->get('pages');
$dataString='';
foreach($row->result() as $r){
$id = $r->id;
$info = $r->info;
$dataString .= $id.'|'.$info.'||';
}
echo json_encode($dataString);
}
}
view part
function request_page(pn)
{
var rpp = <?php echo $rpp; ?>; // results per page
var last = <?php echo $last; ?>; // last page number
var results_box = document.getElementById("results_box");
var pagination_controls = document.getElementById("pagination_controls");
results_box.innerHTML = "loading results ...";
$.ajax({
type: "POST",
url: "<?php echo site_url('search/ajax')?>",
data: { 'rpp' : rpp , 'last' : last, 'pn' : pn},
dataType: "text",
success: function(msg){
// alert(msg)
;
var dataArray = msg.split("||");
var html_output = "";
for(i = 0; i < dataArray.length - 1; i++){
var itemArray = dataArray[i].split("|");
html_output += "ID: "+itemArray[0]+" - Testimonial from <b>"+itemArray[1]+"</b><hr>";
}
results_box.innerHTML = html_output;
}
});
var paginationCtrls = "";
if(last != 1){
if (pn > 1) {
paginationCtrls += '<button onclick="request_page('+(pn-1)+')"><</button>';
}
paginationCtrls += ' <b>Page '+pn+' of '+last+'</b> ';
if (pn != last) {
paginationCtrls += '<button onclick="request_page('+(pn+1)+')">></button>';
}
}
pagination_controls.innerHTML = paginationCtrls;
}
its easy
you should have a view to encode the data to json. Its just this:
<?php
$this->output->set_header('Content-Type: application/json; charset=utf-8');
echo json_encode($json);
In the controller you just have to load this view with an array as parameter (i think that stdClass is also valid):
$data['json'] = array("foo" => "bar", "bar" => "foo");
$this->load->view('your_json_view', $data);

unable to fetch all values from ajax GET method

<script type="text/javascript">
function bindCity() {
// Some javascript code
//declare options array and populate
var modelnames = new Array();
$.get("file.php?mt=" + qs, function(data) {
eval(data);
if(modelnames.length > 0) {
addOptions(modelnames);
}
}
);
}
function addOptions(cl) {
//enable child select and clear current child options
$("#mn").removeAttr("disabled");
$("#mn").html('');
//repopulate child list with array from helper page
var city = document.getElementById('mn');
for(var i = 0; i < cl.length; i++) {
city.options[i] = new Option(cl[i].text, cl[i].value);
}
}
</script>
This is the PHP script (After getting the values to $mt):-
$SQLqueryTry = "SELECT mn FROM pd WHERE pd_mt = '$mt'";
$SQLqueryETry = mysql_query($SQLqueryTry, $dacreint) or die(mysql_error());
while ($Try = mysql_fetch_array($SQLqueryETry))
{
$output = "modelnames.push(new Option('$Try[mn]', '$Try[mn]'));\n";
}
My output code in PHP file:-
header('Content-type: text/plain');
echo $output;
Now i am able to fetch only one value when it is $output = "modelnames.push(new Option('$Try[mn]', '$Try[mn]'));\n";
However when i add . to $output =, to make it $output .= "modelnames.push(new Option('$Try[mn]', '$Try[mn]'));\n";
I am unable to get any value. What is the problem?
Are you able to see any errors in your error log?
My first guess is that you've forgotten to initialize the $output variable before using .= on it.
Maybe try:
$output = "";
while ($Try = mysql_fetch_array($SQLqueryETry))
{
$output .= "modelnames.push(new Option('$Try[mn]', '$Try[mn]'));\n";
}

video swf loading files through php and actionscript from mysql database

I am trying to create a video that loads the videos stred in a directory, depenant on the users id etc.
To do this, I am using php. However, I cannot then get the php to convert to xml within the actionscript:
Here is php code:
$query = "SELECT * FROM video_files ORDER BY video_id DESC";
$resultID = mysql_query($query) or die("Data not found.");
$xml_output = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
$xml_output .= "<PLAYLIST VIDEO_X=\"0\" VIDEO_Y=\"0\" >\n";
for($x = 0 ; $x < mysql_num_rows($resultID) ; $x++){
$row = mysql_fetch_assoc($resultID);
$xml_output .= "<VIDEO TITLE=\"".$row['title']."\" THUMB=\"\" URL=\"".$row['path']."\"/>\n";
}
$xml_output .= "</PLAYLIST>";
echo $xml_output;
here is actionscript:
import fl.video.*;
var thumb_width:Number;
var thumb_height:Number;
var thumbs_x:Number;
var thumbs_y:Number;
var video_x:Number;
var video_y:Number;
var my_videos:XMLList;
var my_total:Number;
var main_container:Sprite;
var thumbs:Sprite;
var titles:Sprite;
var my_player:FLVPlayback;
var myXMLLoader:URLLoader = new URLLoader();
myXMLLoader.load (new URLRequest("playlist.php"));
myXMLLoader.addEventListener (Event.COMPLETE, processXML);
function processXML (e:Event):void {
var myXML:XML = new XML(e.target.data);
thumb_width = myXML.#THUMB_WIDTH;
thumb_height = myXML.#THUMB_HEIGHT;
thumbs_x = myXML.#THUMBS_X;
thumbs_y = myXML.#THUMBS_Y;
video_x = myXML.#VIDEO_X;
video_y = myXML.#VIDEO_Y;
my_videos = myXML.VIDEO;
my_total = my_videos.length();
makeContainers ();
callThumbs ();
makePlayer ();
}
function makeContainers ():void {
main_container = new Sprite();
addChild (main_container);
thumbs = new Sprite();
thumbs.addEventListener (MouseEvent.CLICK, playVideo);
thumbs.addEventListener (MouseEvent.MOUSE_OVER, onOver);
thumbs.addEventListener (MouseEvent.MOUSE_OUT, onOut);
thumbs.x = thumbs_x;
thumbs.y = thumbs_y;
thumbs.buttonMode = true;
main_container.addChild (thumbs);
titles = new Sprite();
titles.x = thumbs_x;
titles.y = thumbs_y;
main_container.addChild (titles);
}
function callThumbs ():void {
for (var i:Number = 0; i < my_total; i++) {
var thumb_url = my_videos[i].#THUMB;
var thumb_loader = new Loader();
thumb_loader.name = i;
thumb_loader.load (new URLRequest(thumb_url));
thumb_loader.contentLoaderInfo.addEventListener (Event.COMPLETE, thumbLoaded);
thumb_loader.y = (thumb_height+10)*i;
var thumb_title = my_videos[i].#TITLE;
var title_txt:TextField = new TextField();
title_txt.text = thumb_title;
title_txt.y = thumb_loader.y;
title_txt.x = thumb_width + 10;
title_txt.width = thumb_width;
title_txt.height = thumb_height;
title_txt.wordWrap = true;
titles.addChild (title_txt);
}
}
function thumbLoaded (e:Event):void {
var my_thumb:Loader = Loader(e.target.loader);
thumbs.addChild (my_thumb);
}
function makePlayer ():void {
my_player = new FLVPlayback();
my_player.skin ="videos/videoskin.swf";
my_player.skinBackgroundColor = 0xAEBEFB;
my_player.skinBackgroundAlpha = 0.9;
my_player.x = video_x;
my_player.y = video_y;
my_player.width = 500;
my_player.height = 400;
main_container.addChild (my_player);
my_player.source = my_videos[0].#URL;
}
function playVideo (e:MouseEvent):void {
var video_url = my_videos[e.target.name].#URL;
my_player.source = video_url;
}
function onOver (e:MouseEvent):void {
var my_thumb:Loader = Loader(e.target);
my_thumb.alpha = 0.5;
}
function onOut (e:MouseEvent):void {
var my_thumb:Loader = Loader (e.target);
my_thumb.alpha = 1;
}
anyone know where i am going wrong? It works with a normal xml file just not php
The format for your XML output in PHP is wrong. Every tag must be closed.
You have:
<?xml version="1.0" encoding="utf-8"?>
<PLAYLIST VIDEO_X="0" VIDEO_Y="0">
<VIDEO TITLE="videotitle" THUMB="thumbnail" URL="URL" />
</PLAYLIST>
You need to close the video tag. So output should look like this:
<?xml version="1.0" encoding="utf-8"?>
<PLAYLIST VIDEO_X="0" VIDEO_Y="0">
<VIDEO TITLE="videotitle" THUMB="thumbnail" URL="URL"></VIDEO>
</PLAYLIST>
You should also set the content-type for your PHP script.
header('Content-type: text/xml');
I don't have access to my laptop to thoroughly test your code, but this is my answer from a first glance at your code.

Categories