Trouble sending an generated jsPdf to server - javascript

I have generated an PDF using jsPdf and Html2Canvas. It works very well, and is downloadable.
I'm now aiming to get the generated .pdf saved to my server, so I can send it out via phpmailer. This is how I approached this.
function print() {
document.getElementById("out").textContent = document.getElementById("fader").value;
const filename = 'DHC_Herren_Front.pdf';
html2canvas(document.querySelector('#pdf')).then(canvas => {
let pdf = new jsPDF('l', 'mm', 'a4');
pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, 298, 211, function () {
var blob = doc.output('blob');
var formData = new FormData();
formData.append('pdf', blob);
$.ajax('/st/tda/dhc/men_front/upload.php', {
method: 'POST',
data: formData,
processData: false,
contentType: false,
success: function (data) {
console.log(data)
},
error: function (data) {
console.log(data)
}
});
});
});
}
and my upload.php
<?php move_uploaded_file(
$_FILES['pdf']['tmp_name'],
$_SERVER['DOCUMENT_ROOT'] . "/st/tda/dhc/men_front/test.pdf");
?>
My Question would be, why I end up without an File on the Server. I feel like there must be an simple solution to this, but I just can't pinpoint it.
Newest HTML
function ma() {
document.getElementById("out").textContent = document.getElementById("fader").value;
html2canvas(document.querySelector('#pdf')).then(canvas => {
var pdf = btoa(doc.output());
pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, 298, 211,);
$.ajax({
method: "POST",
url: "/st/tda/dhc/men_front/upload.php",
data: {data: pdf},
}).done(function(data){
console.log(data);
});
});
}
Newest upload.php
<?php
if(!empty($_POST['data'])){
$data = base64_decode($_POST['data']);
// print_r($data);
file_put_contents( "test.pdf", $data );
} else {
echo "No Data Sent";
}
exit();

This is how I do it. Take a look and see if you can adapt it to your code. This is the uploadFiles.php that the ajax sends the file to.
<?php
$ds = DIRECTORY_SEPARATOR; // a directory separator
$cid = $_POST["cid"]; // directory name passed from the form as a variable
$rid = $_POST["rid"]; // directory name passed from the form as a variable
$storeFolder = "../recordFiles/".$cid."/".$rid; // the place where i want to save stuff
// run only if there are files sent from ajax.
if (!empty($_FILES)) {
// check if the directory exists and if not then create it.
if (!file_exists('../recordFiles/'.$cid."/".$rid)) {
mkdir('../recordFiles/'.$cid."/".$rid, 0777, true);
}
// get the temp file name
$tempFile = $_FILES['file']['tmp_name'];
// remove all whitespace in the file name
$cleanedFileName = $_FILES['file']['name'];
$cleanedFileName = preg_replace('/\s+/', '', $cleanedFileName);
// set the target path
$targetPath = dirname( __FILE__ ).$ds.$storeFolder.$ds;
// set the target file name and path
$targetFile = $targetPath.$cleanedFileName;
// move the files
move_uploaded_file($tempFile,$targetFile);
}
?>

Related

jQuery - Append file name to FormData and get it in a PHP script

I have the following JS code that I use to upload an image based on its path:
var data = new FormData();
data.append('fileName', fileName);
data.append('file', file);
$.ajax({
url : dbPath + "upload-file.php",
type: 'POST',
data: data,
contentType: false,
processData: false,
mimeType: "multipart/form-data",
success: function(data) {
Swal.close();
var fileURL = dbPath + data;
console.log('FILE UPLOADED TO: ' + fileURL);
This is my upload-image.php script:
<?php
$fileName = $_POST['fileName'];
if ($_FILES["file"]["error"] > 0) {
echo "Error: " .$_FILES["file"]["error"]. "<br>";
} else {
// Check file size
if ($_FILES["file"]["size"] > 20485760) { // 20 MB
echo "Sorry, your file is larger than 20 MB. Upload a smaller one.";
} else { uploadImage(); }
}// ./ If
// UPLOAD IMAGE ------------------------------------------
function uploadImage() {
// generate a unique random string
$randomStr = generateRandomString();
$filePath = "uploads/".$randomStr."".$fileName;
// upload image into the 'uploads' folder
move_uploaded_file($_FILES['file']['tmp_name'], $filePath);
// echo the link of the uploaded image
echo $filePath;
}
// GENERATE A RANDOM STRING ---------------------------------------
function generateRandomString() {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i<20; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
?>
Everything works fine in a matter of uploading a file, a JPG image for example, but my purpose is to use:
data.append('fileName', fileName);
to simply append the file name and extension to my FormData and get a file URL like this:
https://example.com/_json/uploads/03aC8qsIk4hanngqO3G4_fileName.jpg
But the $fileName variable in my PHP script fires an error_log line as Undefined index fileName in line xx, so is there a way to upload a file, get its name and extension and append it to the file URL that my PHP script generates?
I hope my question is clear, what I'm trying to do is simply a general Ajax automatic upload for any kind of file, not just images, and get their URL based on a random string + its name and extension (like .png, .mp4, .pdf, etc.).
I've figured it out, thanks to all the comments, I had to append the fileName to my FormData() and edit my PHP script as it follows:
JS:
function uploadFile() {
var dbPath = '<?php echo $DATABASE_PATH ?>';
var file = $("#file")[0].files[0];
var fileName = file.name;
console.log('FILE NAME: ' + fileName);
Swal.fire({icon: 'success', title: 'Loading...', showConfirmButton: false })
var data = new FormData();
data.append('file', file);
data.append('fileName', fileName); <!-- ADDED THIS LINE
$.ajax({
url : dbPath + "upload-file.php?fileName=" + fileName, <!-- ADDED THIS LINE
type: 'POST',
data: data,
contentType: false,
processData: false,
mimeType: "multipart/form-data", <!-- ADDED THIS LINE
success: function(data) {
Swal.close();
var fileURL = dbPath + data;
console.log('FILE UPLOADED TO: ' + fileURL);
// error
if (data.includes("ERROR:")) {
Swal.fire({ icon: 'error', title: 'Oops...', text: data, });
// show file data
} else {
$("#fileURL").val(fileURL);
$("#viewButton").attr("href", fileURL);
$("#viewButton").css("display", "block");
}
// error
}, error: function(e) {
Swal.fire({ icon: 'error', title: 'Oops...', text: 'Something went wrong: ' + e.message, });
}});
}
My upload-file.php script:
<?php include 'config.php';
if ($_FILES["file"]["error"] > 0) {
echo "Error: " .$_FILES["file"]["error"]. "<br>";
} else {
// Check file size
if ($_FILES["file"]["size"] > 20485760) { // 20 MB
echo "ERROR: Your file is larger than 20 MB. Please upload a smaller one.";
} else { uploadImage(); }
}// ./ If
// UPLOAD IMAGE ------------------------------------------
function uploadImage() {
// generate a unique random string
$randomStr = generateRandomString();
$filePath = "uploads/".$randomStr;
// upload image into the 'uploads' folder
move_uploaded_file($_FILES['file']['tmp_name'], $filePath);
// echo the link of the uploaded image
echo $filePath;
}
// GENERATE A RANDOM STRING ---------------------------------------
function generateRandomString() {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i<20; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString."_".$_POST['fileName']; <!-- ADDED THIS LINE
}
?>
Now I can finally upload any type of file and get its name + extension at the end of the URL, it works perfectly.

Store Canvas image filename and/or location path to database whilst saving?

I have a canvas image on my page with a Save button that saves down a PNG image file.
function save() {
var canvas = document.getElementById('drawing');
var dataURL = canvas.toDataURL();
$.ajax({
type: "POST",
url: "canvas_ajax_upload_post.php",
data: { img: dataURL }
}).done(function(msg){
alert(msg);
});
}
The canvas_ajax_upload_post.php looks like this:
<?php
$img = $_POST['img'];
if (strpos($img, 'data:image/png;base64') === 0) {
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = 'uploads/img'.date("YmdHis").'.png';
if (file_put_contents($file, $data)) {
echo "The canvas was saved as $file.";
} else {
echo 'The canvas could not be saved.';
}
}
?>
This works fine, images get saved to the uploads folder on my server. What I have been trying to do is store the filename in my SQL database. I have a hidden form field on my main page that I would like to pass the filename or filepath to after the image has been saved, but I cannot figure out how.
I have tried embedding JavaScript code in the PHP file, but it just treats it as a text string and includes it in the alert popup. Essentially what I am trying to do is use the $file variable from the php file in JavaScript code.
E.g. document.getElementById("hidden_form_field").value = $file;
Can anybody help?
You can pass the filename in the data object:
function save() {
var canvas = document.getElementById('drawing');
var dataURL = canvas.toDataURL();
$.ajax({
type: "POST",
url: "canvas_ajax_upload_post.php",
data: {
img: dataURL,
filename: document.getElementById("hidden_form_field").value
}
}).done(function(msg){
alert(msg);
});
}
Then retrieve the "filename" variable by getting $_POST["filename"]:
<?php
$img = $_POST['img'];
$filename = $_POST['filename'];
if (strpos($img, 'data:image/png;base64') === 0) {
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = 'uploads/img'.date("YmdHis").'.png';
if (file_put_contents($file, $data)) {
echo "The canvas was saved as $file.";
} else {
echo 'The canvas could not be saved.';
}
// DO SOME SQL QUERY W/ $filename variable
// SQL CODE HERE
}
?>
You'll need include your SQL query code to use the $filename variable. I didn't see that code in your question.
By what I understand from your question, you're trying to get the value of $file back form php.
You can return the value via the msg variable (which is what php echos) in your $.ajax.done function.
For example:
function(msg){
alert(msg);
if(msg.search("The canvas was saved as")!=-1){//was saved
document.getElementById("hidden_field").value=msg.slice(23);//assuming string "The canvas was saved as $file."
}
}

Generate and download CSV file with php and ajax

I have a php page that creates a CSV file that is then downloaded by the browser automatically. Here is a version with sample data - it works great.
<?php
$cars = array(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=csvfile.csv');
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// output the column headings
fputcsv($output, array('Car', 'Year', 'Miles' ));
//Loop through the array and add to the csv
foreach ($cars as $row) {
fputcsv($output, $row);
}
?>
I would like to be able to run this from another page using ajax so that a user can generate/download a csv without leaving the main page. This is the JavaScript I am using on the main page. In my real page I am using the data coming via ajax.
$('button[name="exportCSVButton"]').on('click', function() {
console.log('click');
$.ajax({
url: 'exportCSV.php',
type: 'post',
dataType: 'html',
data: {
Year: $('input[name="exportYear"]').val()
},
success: function(data) {
var result = data
console.log(result);
}
});
});
When I click the button to trigger the script, it runs, but instead of saving/download to csv it prints the entire thing to console. Is there any way to accomplish what I want? Without actually saving the file to the server and reopening.
I have done csv file download via ajax
PHP Code
<?php
function outputCsv( $assocDataArray ) {
if ( !empty( $assocDataArray ) ):
$fp = fopen( 'php://output', 'w' );
fputcsv( $fp, array_keys( reset($assocDataArray) ) );
foreach ( $assocDataArray AS $values ):
fputcsv( $fp, $values );
endforeach;
fclose( $fp );
endif;
exit();
}
function generateCsv(){
$res_prods = $wpdb->get_results( "SELECT * FROM `{$wpdb->prefix}products` ", OBJECT );
$products= [];
foreach ($res_prods as $key => $product) :
$product_id = $product->ID;
$products[$product_id]['product_id'] = $product_id;
$products[$product_id]['name'] = $product->name;
endforeach;
return outputCsv( $products);
}
jQuery AJAX
jQuery(document).on( 'click', '.btn_generate_product', function(e) {
var product_id = jQuery(this).data('product_id');
jQuery.ajax({
url : "ajaxurl",
type: 'POST',
data: { product_id },
success: function(data){
/*
* Make CSV downloadable
*/
var downloadLink = document.createElement("a");
var fileData = ['\ufeff'+data];
var blobObject = new Blob(fileData,{
type: "text/csv;charset=utf-8;"
});
var url = URL.createObjectURL(blobObject);
downloadLink.href = url;
downloadLink.download = "products.csv";
/*
* Actually download CSV
*/
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
}
});
});
Replace console.log(result); with file save code.
check here JavaScript: Create and save file
The best way to save file with browser dialog box, use simple code.
<a href="#" onclick="window.open('exportCSV.php?year=' + $('input[name="exportYear"]').val())" >Download File</a>
I did it time ago by creating a hidden iframe and via javascript the source of the iframe was set to a php file which sent the appropriate headers and data as your exportCSV.php does.
But, if you don't like this idea, you could use a library like jQuery File Download or FileSaver.js

View pdf report from ajax request

I have a problem generating a pdf with the TCPDF library, and tried to follow some examples that are here, but I have not managed to solve my problem, which is this: when I click on a button I am making an AJAX request Which sends a parameter and the url points to a controller in php with CODEIGNITER, the parameter is used to execute my query and generate the report based on it. I have already debugged the report with static parameters to see if it worked and without using AJAX, and everything went well. The problem is that I need to send the data this way and I do not know how to load the pdf file created in the response of my request, any ideas?
$("#BtnDownload").click(function (){
var jsonString = 2; //Example parameters;
$.ajax({
type: 'POST',
url: baseurl+"reports/selectReport",
data: {'data': jsonString},
success: function(response){
//What my driver should return
}
});
});
This is the function in my controller that I point my ajax request, I do not put all the code of the layout of my report because it is working, and the code is very long, the important thing is to know how to return my generated report And can view it from the browser.
public function selectReport(){
$this->load->library('Pdf');
$pdf = new Pdf('L', 'mm', 'A4', true, 'UTF-8', false);
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetTitle('report');
$pdf->SetSubject('Report PDF');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->setPrintHeader(false);
$pdf->setFooterData($tc = array(0, 64, 0), $lc = array(0, 64, 128));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
$pdf->SetFont('dejavusans', '', 12, '', true);
$base_url = base_url();
$data = $this->input->post("data");
// report body
$name_pdf = utf8_decode("report.pdf");
$pdf->Output($name_pdf, 'I');
}
In TCPDF ( according to TCPDF Save file to folder? ) the PDF can be saved:
$dir = 'pdfs/';
$filename = 'report' . microtime(TRUE) . '.pdf';
if( ! is_dir( FCPATH . $dir ) )
mkdir( FCPATH . $dir, 0777, TRUE );
$pdf->Output( FCPATH . $dir . $filename, 'F'); // F saves to filesystem
Since you know the PDFs are in the pdf directory:
$this->load->helper('url');
echo json_encode(array(
'path' => FCPATH . $dir . $filename,
'url' => base_url( $dir . $filename )
));
Then in your ajax success function data.url is the URL to the file:
success: function(response){
if( response.url ){
window.location = response.url;
}
}
Make sure your $.ajax has the configuration for dataType: 'json'.
$.ajax({
// ...
dataType: 'json'
// ...
});

File upload by ajax $.post not working

I am really new to ajax do forgive me if the question is stupid. I have a multi step form and it has the 4 parts , and I am using $.post() ajax request to send this. while all my other details are going fine I am not able to upload my file. this is what I am trying to do
Here I am trying to catch the form values.
var data_img = new FormData();
var hello = $.each(jQuery('#pan_file')[0].files, function (i, file) {
data_img.append('file-' + i, file);
});
Then I am passing these values to the object variable.
obj_params.pan_file = hello;
And then sending it to store with ajax.post()
$.post('<?php echo base_url(); ?>get-ekyc-form', obj_params, function (msg) {
if (msg == "1") {
swal("Success!", "EKYC Form has been Submitted Successfully", "success");
window.location = '<?php echo base_url(); ?>list-active-requirement';
}
}, "json", "processData:false", "contentType:false");
return true;
And this is where I do file transfer.
if ($_FILES['file-0']['name'] != "") {
$image_data = array();
//config initialise for uploading image
$config['upload_path'] = './media/front/img/quote-docs/';
$config['allowed_types'] = 'xlsx|pdf|doc|docx';
$config['max_size'] = '5000';
$config['max_width'] = '12024';
$config['max_height'] = '7268';
$config['file_name'] = time();
//loading upload library
$this->upload->initialize($config);
$this->load->library('upload', $config);
if (!$this->upload->do_upload('file-0')) {
$error = array('error' => $this->upload->display_errors());
} else {
$data = array('upload_data' => $this->upload->data());
$image_data = $this->upload->data();
$file_name = $image_data['file-0'];
}
$file_name = $image_data['file_name'];
} else {
$file_name = '';
}
Also I am working on someone elses code so I do understand I must have made loads of mistakes. I'll be grateful if someone could help me around this.
HTML code
<input id="picture" type="file" name="pic" />
<button id="upload">Upload</button>
$('#upload').on('click', function() {
var file_data = $('#picture').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
$.ajax({
url: 'upload.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert(php_script_response); // display response from the PHP script, if any
}
});
});
in upload.php
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
?>

Categories