Send variable to tcpdf jQuery - php

I want to send some html content via jQuery to tcpdf and create an pdf.
I have this in my index.php:
$('#test').click(function() {
var result='hello';
$.ajax({
type: 'POST',
url: 'pdf.php',
data: {result: result},
});
})
and the pdf.php:
<?php
$result = '';
if(isset($_POST['result'])) {
$result = $_POST['result'];
}
require_once('tcpdf/tcpdf.php');
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetTitle('Production sheet');
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH);
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
$pdf->SetFont('helvetica', '', 9);
$pdf->AddPage();
$html = '
<h1>TEST</h1>
<table>
<tr><td>'.$result.'</td></tr>
</table>
';
$pdf->writeHTML($html, true, 0, true, 0);
$pdf->lastPage();
$pdf->Output('test.pdf', 'I');
?>
If I define variable result ($result = "Hello";) and i run directly pdf.php it's working perfect. It seems that for some reason my post isn't taken by pdf.php... Some ideas?
Thank you!

I did say I'm too tired. As #andrew pointed out you were using inline output instead of download and in an Ajax call that won't really work. Reading through the comments if you want to Download the PDF and POST values to it here is my suggestions:
1) Create a FORM in your HTML
<form action='pdf.php' method=post target=_blank id=myform>
</form>
2) If you need to add data with Javascript then change your jQuery code as follow:
$('#test').click(function() {
var result='hello';
$("#my_form").append("<input type=hidden name=result value='"+result+'>");
$("#my_form").submit();
});
3) Adjust the pdf.php to use $_POST instead of $_GET
You should consider if you really need an jQuery for this. If the result variable in your javascript get populated from user inputted form values you might just re-design your page and include all that in the form without the need of any additional jQuery at all.

You're using
$pdf->Output('test.pdf', 'I');
I meaning destination: Inline. See the manual
You either have to use option F and specify a file name on the server then redirect the user to that filename or use option D to force a download.
Something like:
$('#test').click(function() {
var result='hello';
window.open('/pdf.php?result='+result, '_blank');
});
And
<?php
$result = '';
if(isset($_GET['result'])) {
$result = $_GET['result'];
}
.....
$pdf->Output('test.pdf', 'D');
EDIT
For large amounts of data you would be better to use the ajax method you were experimenting with, but handling the returned pdf document in the ajax response would be tricky, it is probably doable with a javascript file reader
As simpler option would look something like this:
$('#test').click(function() {
var result='hello';
$.ajax({
type: 'POST',
url: 'pdf.php',
data: {result: result},
}).done(function(filename){
$('#testDiv').html('<a target="_blank" href="/'+filename+'">download your pdf</a>');
});
})
And
<?php
$result = '';
if(isset($_POST['result'])) {
$result = $_POST['result'];
}
....
$filename = time().'.pdf';
$pdf->Output($filename, 'F');
echo $filename;
so whats happening is you're creating pdf files on the server and appending a link to the page using ajax, its not the best solution as it leaves all pdf files on the server and the user only gets to see the link once.
Should hopefully give you some ideas though.

Related

php and styled html table to pdf

i have this code generating a styled table but uses php to grab info for the table from a database.
<form name="pt_list" action="classes/MYPDF.php" method="post"><br/>
<input type="submit" name="pdf" value="Download as PDF">
</form>
<?php
ob_start();
?>
<table id=patients>
<tr>
<th>Pt. username</th>
<th>Pt. number</th>
<th>Full Name</th>
<th>Added on</th>
</tr>
<?php $x=1;
foreach ($users as $patient) {
?> <tr <?php if ($x % 2 == 0) {echo "class='alt'"; } ?>>
<td> <?php echo $patient['username'];?></td>
<td> <?php echo $patient['id'];?></td>
<td> <?php echo $patient['name'];?></td>
<td> <?php echo $patient['joined'];?></td>
</tr>
<?php
$x++;
} ?>
</table>
<?php
$GLOBALS['table'] = ob_get_clean();
$table = $GLOBALS['table'];
?>
i am trying to grab this table and offer it to users to download as a pdf. i tried tcpdf and fpdf but always keep getting cannot send pdf, output already sent. Here is my code for MYPDF.php:
<?php
//============================================================+
// File name : example_003.php
// Begin : 2008-03-04
// Last Update : 2013-05-14
//
// Description : Example 003 for TCPDF class
// Custom Header and Footer
//
// Author: Nicola Asuni
//
// (c) Copyright:
// Nicola Asuni
// Tecnick.com LTD
// www.tecnick.com
// info#tecnick.com
//============================================================+
/**
* Creates an example PDF TEST document using TCPDF
* #package com.tecnick.tcpdf
* #abstract TCPDF - Example: Custom Header and Footer
* #author Nicola Asuni
* #since 2008-03-04
*/
// Include the main TCPDF library (search for installation path).
require_once('../tcpdf/tcpdf.php');
// Extend the TCPDF class to create custom Header and Footer
class MYPDF extends TCPDF {
//Page header
public function Header() {
// Logo
$image_file = K_PATH_IMAGES.'logo_example.jpg';
$this->Image($image_file, 10, 10, 15, '', 'JPG', '', 'T', false, 300, '', false, false, 0, false, false, false);
// Set font
$this->SetFont('helvetica', 'B', 20);
// Title
$this->Cell(0, 15, '<< TCPDF Example 003 >>', 0, false, 'C', 0, '', 0, false, 'M', 'M');
}
// Page footer
public function Footer() {
// Position at 15 mm from bottom
$this->SetY(-15);
// Set font
$this->SetFont('helvetica', 'I', 8);
// Page number
$this->Cell(0, 10, 'Page '.$this->getAliasNumPage().'/'.$this->getAliasNbPages(), 0, false, 'C', 0, '', 0, false, 'T', 'M');
}
}
// create new PDF document
$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Nicola Asuni');
$pdf->SetTitle('TCPDF Example 003');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, PDF_HEADER_STRING);
// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
// set some language-dependent strings (optional)
if (#file_exists(dirname(__FILE__).'/lang/eng.php')) {
require_once(dirname(__FILE__).'/lang/eng.php');
$pdf->setLanguageArray($l);
}
// ---------------------------------------------------------
// set font
$pdf->SetFont('times', 'BI', 12);
// add a page
$pdf->AddPage();
// set some text to print
// print a block of text using Write()
$pdf->writeHTML($GLOBALS['table'], true, false, true, false, '');
// ---------------------------------------------------------
//Close and output PDF document
$pdf->Output('example_003.pdf', 'D');
//============================================================+
// END OF FILE
this is the error i get: Notice: Undefined index: table in /Users/Tika/PhpstormProjects/ooplr/classes/MYPDF.php on line 105
TCPDF ERROR: Some data has already been output, can't send PDF file.
Any input would be greatly appreciated.
Notice: Undefined index: table in /Users/Tika/PhpstormProjects/ooplr/classes/MYPDF.php on line 105
This means that $GLOBALS['table'] is undefined, holds no data. What happens when you change the writeHTML row to something like 'test' instead of $GLOBALS['table']?
Are you sure the variable is filled with the table HTML in the first place? Try going to the top of mypdf.php and write var_dump($GLOBALS['table']); exit; after the initial < ?php tag. Does it output anything?
TCPDF ERROR: Some data has already been output, can't send PDF file.
This is due to the fact that you can't generate and output a PDF if you already printed something out in the document. In this case, I think it's a follow on error since an error has been outputed to the document, you can't make it a pdf any longer. It may also have to do with something as stupid as a whitespace character before the initial < ?php.
If I understand the situation correctly, I think your problem is moving the table data from the html file to MYPDF.php. If that's the case, I'd consider an alternative solution:
<form name="pt_list" action="classes/MYPDF.php" method="post"><br/>
<?php foreach ($users as $patient) {
echo '<input type="hidden" name="patients[]" value="'.$patient['id'].'">';
} ?>
<input type="submit" name="pdf" value="Download as PDF">
</form>
This will give you a hidden input field for every patient, and let's you send forth the data to the form target (in this case, mypdf.php). Since I'm using [ ] in the name field, php will recognize many fields can use this name and will make the result an array. In mypdf.php you can now reach this data through the magic variable $_POST['patients']. You can foreach this data or reach the data individually like so: $_POST['patients'][0] ... [1] etc...
You can do the same to get the username, name, joined data through as well, or you can use the ID to fetch the data from the database again. If you get this far, I'm sure you'll figure out the rest on your own.
This is my first response so please let me know if I'm not being helpful, or let me know if there's anything you don't understand.

TCPDF and FPDI with multiple pages

This looks like the simplest thing but I can't get it to work.
I need to add text to the first page of a multi-page pdf (could be any number of pages)
Using this code on a two page pdf (without the for loop, just using $pdf->importPage(2)) I end up with two pages but the second page is a repeat of page one. The text is written on the first page only which is good but I need all pages included in the output pdf. Here is my code
// Original file with multiple pages
$fullPathToFile = 'full/path/to/file.pdf';
class PDF extends FPDI {
var $_tplIdx;
function Header() {
global $fullPathToFile;
if (is_null($this->_tplIdx)) {
$this->setSourceFile($fullPathToFile);
$this->_tplIdx = $this->importPage(1);
}
$this->useTemplate($this->_tplIdx);
}
function Footer() {}
}
// initiate PDF
$pdf = new PDF();
$pdf->setFontSubsetting(true);
// add a page
$pdf->AddPage();
// The new content
$pdf->SetFont("helvetica", "B", 14);
$pdf->Text(10,10,'Some text here');
// How to get the number of pages of original pdf???
// $numPages = $pdf->getNumPages(???);
// Carry on adding all remaining pages starting from page 2
for($i=2;$i<=$numPages;$i++) {
// Add another page
$pdf->AddPage();
// Do I need to declare the source file here?
// $pdf->setSourceFile($fullPathToWD);
$pdf->importPage($i);
}
// Output the file as forced download
$pdf->Output('theNewFile.pdf', 'D');
Links to docs
TCPDF Classes
http://www.tcpdf.org/doc/code/classTCPDF.html#a5171e20b366b74523709d84c349c1ced
FPDI Classes
http://www.setasign.de/support/manuals/fpdi/
FPDF_TPL Classes
http://www.setasign.de/support/manuals/fpdf-tpl/
Solved my problem...
// Original file with multiple pages
$fullPathToFile = 'full/path/to/file.pdf';
class PDF extends FPDI {
var $_tplIdx;
function Header() {
global $fullPathToFile;
if (is_null($this->_tplIdx)) {
// THIS IS WHERE YOU GET THE NUMBER OF PAGES
$this->numPages = $this->setSourceFile($fullPathToFile);
$this->_tplIdx = $this->importPage(1);
}
$this->useTemplate($this->_tplIdx);
}
function Footer() {}
}
// initiate PDF
$pdf = new PDF();
$pdf->setFontSubsetting(true);
// add a page
$pdf->AddPage();
// The new content
$pdf->SetFont("helvetica", "B", 14);
$pdf->Text(10,10,'Some text here');
// THIS PUTS THE REMAINDER OF THE PAGES IN
if($pdf->numPages>1) {
for($i=2;$i<=$pdf->numPages;$i++) {
$pdf->endPage();
$pdf->_tplIdx = $pdf->importPage($i);
$pdf->AddPage();
}
}
// Output the file as forced download
$pdf->Output('theNewFile.pdf', 'D');
You get the number of pages by adding the first part of this line
$this->numPages = $this->setSourceFile($fullPathToFile);
And see the second last block of code - the for loop adds the remainder of the pages.
Don't know if this is how it should be done? I read in a few places that it wasn't even possible to achieve this, also the code is not supplied in the docs. However, this works, hope it helps someone.
I struggled with this a little and tried to come up with simplest way to add some text to the last page of a multi-page document. Here is the very simple code that worked for me:
require_once('fpdf/fpdf.php');
require_once('fpdf/fpdi.php');
$pdf = new FPDI();
$fullPathToPDF = '/usr/local/common/my.pdf';
$pageCount = $pdf->setSourceFile($fullPathToPDF);
for ($i = 1; $i <= $pageCount; $i++) {
$pdf->importPage($i);
$pdf->AddPage();
$pdf->useTemplate($i);
}
$pdf->SetFont('Helvetica');
$pdf->SetXY(110, 225);
$pdf->Write(8, 'A complete document imported with FPDI');
$pdf->Output($fullPathToPDF);
Just change the full path to file to a location where you have a multi-page PDF.
$pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
...
$pdf->SetMargins(10, 10, 10);
$pdf->SetAutoPageBreak(true, 10);
foreach($array as $item)
{
$pdf->AddPage(); //add new page for new item
$txt = some_long_long_text;
$pdf->Write(0, $txt, '', 0, 'C', true);
$pdf->endPage(); //do end of page
$pdf->lastPage(); //set cursor at last page, because autopagebreak not do it
}
In example, you have 10 pupils in array, and you need create resume for each. In exam, one resume have 3 pages. So in out u get pdf with 30 pages, with correct text.
SetAutoPageBreak(true, 10), not set cursor at last page, so you need to do it manually with function $pdf->lastPage();
that code wont work, try this:
$pdf = new PDI();
$pdf->AddPage();
$pdf->setSourceFile('zzz.pdf');
$pdf->numPages = $pdf->setSourceFile('zzz.pdf');
$tplIdx = $pdf->importPage(1);
$pdf->useTemplate($tplIdx, 10, 20, 200);
if($pdf->numPages>1) {
for($i=2;$i<=$pdf->numPages;$i++) {
$pdf->AddPage();
$tplIdx = $pdf->importPage($i);
$pdf->useTemplate($tplIdx, 10, 20, 200);
}
}

TCPDF set different headers for different pages in one document

Is there a way to have a different header logo for the 1st page in a document and different for the 2nd page?
I thought that changing the header data between adding pages might do the trick, but in my tests it seems that setting the header after adding the first page has no effect:
/* other stuff
$pdf->setHeaderFont(array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
$pdf->AliasNbPages();
*/
$pdf->SetHeaderData("logo_1.png", PDF_HEADER_LOGO_WIDTH, '', '');
$pdf->AddPage();
$pdf->writeHTML($htmlContent, true, 0, true, true);
$pdf->SetHeaderData("logo_2.png", PDF_HEADER_LOGO_WIDTH, '', '');
$pdf->AddPage();
$pdf->writeHTML($htmlContent2, true, 0, true, true);
The above produces a document with 2 pages, both having logo_1.png in header.
Will I need to customize TCPDF itself? Has anyone done this? I'm using version 5.9.144.
Strange. I'm having the same issue, but this worked in my older version of TCPDF version:4.8.009 and I noticed the issue when I upgraded to 5.9.149.
I compared the 2 and isolated the issue to the Header() function.
I could force it to allow me to change the header and accept it by running this:
$pdf->setHeaderTemplateAutoreset(true);
The following worked for me,
class MYPDF extends TCPDF{
function header1(){
//print whatever the header 1 is
}
function Header2(){
if($this->page==1){
//print header 1 and whatever the header 2 is
}else{
//print just header 2
}
}
}
I used:
$pdf->resetHeaderTemplate();
It should override the template header and assign the new one according to need. It worked for me.
How about... have TCPDF generate pages with different headers as separate documents, and then use something to merge all those intermediate PDFs together to form the final document's pages (maybe even TCPDF itself can merge, I don't know)?
A couple of "how to merge?" results:
Merge PDF files with PHP
Merge files into a single PDF using PHP/linux
If you wish to have a cover page without header and footer and internal pages with them, there is an easier way to handle it.
Simply turn off the header and footer print via 'setPrintHeader' and 'setPrintFooter' as follows:
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->AddPage();
$pdf->SetFont("freesans", "B", 20);
$pdf->Cell(0,10,"COVER TEXT",1,1,'C');
$pdf->setPrintHeader(true);
$pdf->setPrintFooter(true);
$pdf->setHeaderFont(array("freesans", "", 9));
$pdf->SetHeaderData('', '', 'Document Title', 'Document Header Text');
$pdf->AddPage();
$pdf->SetFont("freesans", "B", 20);
$pdf->Cell(0,10,"Internal text",1,1,'C');
$pdf->Output("HappyCover.pdf", "I");
Enjoy!
Just for the record, if someone has the same problem in the future and can use Zend_Pdf:
// $filename is the final filename with path to save the generated PDF
$dir = dirname($filename);
$base = basename($filename);
$page1 = $dir . DIRECTORY_SEPARATOR . "tmp_1_" . $base;
$page2 = $dir . DIRECTORY_SEPARATOR . "tmp_2_" . $base;
//creates 1st page with TCPDF and saves to filesystem with filename $page1
$this->generateInvoicePage1($html_1, $page1);
//creates 2nd page with TCPDF and saves to filesystem with filename $page2
$this->generateInvoicePage2($html_2, $page2);
$pdf1 = Zend_Pdf::load($page1);
$pdf2 = Zend_Pdf::load($page2);
foreach ($pdf2->pages as $page) {
$pdf1->pages[] = clone($page);
}
$pdf1->save($filename);
unlink($page1);
unlink($page2);
I found this to be the solution with the lightest touch:
class MYPDF extends TCPDF {
//Page header
public function AddNewHeader($newTitle) {
$this->header_xobj_autoreset = true;
$this->header_title = $newTitle;
}
}
Be sure to call TCPDF::setHeaderData() first. Next, call this function before every AddPage() event, or, if you're looping through data and relying on tcpdf to add pages, call it after every element add. It breaks the caching of the header, but allows the user to put a new and custom header on each page. All the elements returned by TCPDF::getHeaderData() can be updated in this way.
my solution, with just a condition
function Header(){
if($this->page==1){
$html = '<div><img src="./outils/img1.png" alt=""></div>';
$this->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
}else{
$html = '<div><img src="./outils/img2.png" alt=""></div>';
$this->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
}
}

Script to draw image

I am looking for a PHP script that will allow me to draw an image with my mouse and save it as an image. If you know of any please help.
In case you do feel like reinventing a few wheels :-)
Make a Javascript snippet that lets you draw. This can of course be as advanced or simple as you wish, for example:
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
pos = false;
ctx.strokeStyle = "red";
$(canvas).bind("mousedown", function(evt) {
pos = {x: evt.layerX, y: evt.layerY};
ctx.beginPath();
ctx.moveTo(pos.x, pos.y);
});
$(canvas).bind("mousemove", function(evt) {
if(!pos) return; // You may not want to do this on every mousemove.
pos = {x: evt.layerX, y: evt.layerY};
ctx.lineTo(pos.x, pos.y);
ctx.stroke();
});
$(canvas).bind("mouseup", function(evt) {
if(!pos) return;
ctx.closePath();
pos = false;
});
Also add a button that sends the image data to your PHP script:
$('#btn').bind("click", function(evt) {
$.post('saveImage.php', {image : canvas.toDataURL('image/jpeg')});
});
In your saveImage.php script on the server, decode the data and write it to a file.
$imgData = $_POST["image"]; // Probably a good idea to sanitize the input!
$imgData = str_replace(" ", "+", $imgData);
$imgData = substr($imgData, strpos($imgData, ","));
$file = fopen('myImage.jpg', 'wb');
fwrite($file, base64_decode($imgData));
fclose($file);
Should do the trick :-) I'm using jQuery for the JS bits here, that's of course not necessary.
PHP is executed server-side, whereas interaction with the mouse is carried out client-side. You would need to use an in-browser technology like JavaScript or Flash to capture the mouse movements and generate bitmap data first.

javascript return function's data as a file

I have a function in javascript called "dumpData" which I call from a button on an html page as **onlick="dumpData(dbControl);"* What it does is return an xml file of the settings (to an alert box right now). I want to return it to the user as a file download. Is there a way to create a button when click will open a file download box and ask the user to save or open it? (sorta of like right-clicking and save target as)...
Or can it be sent to a php file and use export();? Not sure how I would send a long string like that to php and have it simple send it back as a file download.
Dennis
I don't think you can do that with javascipt, at least not with a nice solution.
Here's how to force a download of a file in PHP:
$file = "myfile.xml";
header('Content-Type: application/xml');
header("Content-Disposition: attachment; filename='$file'");
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
Instead of using readfile to output your file, you could also directly display content using echo.
/EDIT: hell, someone was faster :).
EDITED:
just a proof of concept.. but you get the idea!
instead of
<a onlick="dumpData(dbControl); href="#">xml file</a>
you can have like this:
xml file
then like this:
// Assuming your js dumpData(dbControl); is doing the same thing,
// retrieve data from db!
$xml = mysql_query('SELECT * FROM xml WHERE id= $_GET['id'] ');
header("Content-type: text/xml");
echo $xml;
I eneded up going this route:
The HTML code
<script type="text/javascript">
$(document).ready(function() {
$("#save").click(function(e) { openDialog() } );
});
</script>
<button id="save" >Send for processing.</button>
The javascript code:
function openDialog() {
$("#addEditDialog").dialog("destroy");
$("#Name").val('');
$("#addEditDialog").dialog({
modal: true,
width: 600,
zIndex: 3999,
resizable: false,
buttons: {
"Done": function () {
var XMLname = $("#Name").val();
var XML = dumpXMLDocument(XMLname,geomInfo);
var filename = new Date().getTime();
$.get('sendTo.php?' + filename,{'XML':XML}, function() {
addListItem(XMLname, filename + ".XML");
});
$(this).dialog('close');
},
"Cancel": function () {
$("#Name").val('');
$(this).dialog('close');
//var XMLname = null;
}
}
});
}
PHP Code, I just decided to write the file out to a directory. Since I created the filename in the javascript and passed to PHP, I knew where it was and the filename, so I populated a side panel with a link to the file.
<?php
if(count($_GET)>0)
{
$keys = array_keys($_GET);
// first parameter is a timestamp so good enough for filename
$XMLFile = "./data/" . $keys[0] . ".kml";
echo $XMLFile;
$fh = fopen($XMLFile, 'w');
$XML = html_entity_decode($_GET["XML"]);
$XML = str_replace( '\"', '"', $XML );
fwrite($fh, $XML);
fclose($fh);
}
//echo "{'success':true}";
echo "XMLFile: ".$XMLFile;
?>
I don't know why, but when I send the XML to my php file it wrote out the contents withs escape charters on all qoutes and double quotes. So I had to do a str_replace to properly format the xml file. Anyone know why this happens?
POST the XML via a form to a php script that writes it back to the client with a Content-Disposition: attachment; filename=xxx.xml header.
<form name="xml_sender" action="i_return_what_i_was_posted.php" method="POST">
<input type="hidden" name="the_xml" value="" />
</form>
Then with js
function dumpData(arg) {
var parsedXML = ??? //whatever you do to get the xml
//assign it to the the_xml field of the form
document.forms["xml_sender"].the_xml.value = parsedXML;
//send it to the script
document.forms["xml_sender"].submit();
}
Can't remember if this loses the original window, if so, post to an iframe.

Categories