Save pdf (from window.print) to js var - javascript

We can generate and save locally a page as pdf with window.print(), but I want to know if I can save a page as pdf in a variable, exactly like window.print() generates a pdf, because I want to send it through ajax after. Thanks.

As i can understand your exact need this can be of your help.
HTML
<button onclick="document.getElementById('opepdf').click();">Read PDF</button>
<input id="opepdf" type="file" name="name" style="display: none;" onchange="PDFReader(event);"/>
Javascript
function PDFReader(e){
var file = e.target.files[0];
var pdfReader = new FileReader();// Create a File Reader
pdfReader.readAsText(file,'UTF-8');
pdfReader.onload = readerEvent => {
var PDFContent = readerEvent.target.result;
console.log( PDFContent );//PDF content in variable
}
}
Don't know if this cross browser or not but it does not need any js plugin.
More elaborate explanation about how you will be using this can improve the answers.
If you want to upload a file through ajax you can use other ways.
EDIT:
If you want to send PDF through ajax to your server use:
HTML:
<form>
Select PDF
<input id="opepdf" name="opepdf" type="file" /><br>
<div id="upload"></div><br>
<input type="submit" value="submit"/>
</form>
JAVA-SCRIPT: need jquery
//form Submit
$("form").submit(function(evt){
evt.preventDefault();
$("#upload").html("<img src='http://crabsheet.com/cs/wp-content/uploads/2012/08/capture-1.gif'>");
var formData = new FormData($(this)[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
data: formData,
async: true,
cache: false,
contentType: false,
enctype: 'multipart/form-data',
processData: false,
success: function (response) {
$("#upload").html(response);
}
});
return false;
});
PHP-Serverside: there should be a "uploads" folder relative to script dir
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["opepdf"]["name"]);
$fileName = $_FILES['opepdf']['name'];
$fileType = $_FILES['opepdf']['type'];
$fileError = $_FILES['opepdf']['error'];
$fileContent = file_get_contents($_FILES['opepdf']['tmp_name']);
if($fileError == UPLOAD_ERR_OK){
//Processes your file here
if (move_uploaded_file($_FILES["opepdf"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["opepdf"]["name"]). " has been uploaded.";
} else {
echo "Error uploading your file.";
}
}else{
switch($fileError){
case UPLOAD_ERR_INI_SIZE:
$message = 'MAX UPLOAD SIZE Reached';
break;
case UPLOAD_ERR_FORM_SIZE:
$message = 'MAX FORM Upload Size Reached';
break;
case UPLOAD_ERR_PARTIAL:
$message = 'Could not finish Upload';
break;
case UPLOAD_ERR_NO_FILE:
$message = 'NO upload File';
break;
case UPLOAD_ERR_NO_TMP_DIR:
$message = 'Servernot configured for file upload';
break;
case UPLOAD_ERR_CANT_WRITE:
$message= 'CANT WRITE';
break;
case UPLOAD_ERR_EXTENSION:
$message = 'Could not finish Upload.';
break;
default: $message = 'Could not finish Upload';
break;
}
echo json_encode(array(
'error' => true,
'message' => $message
));
}
?>

You know you can save a web page as pdf with window.print() so you want to catch the output of window.print() as var in javascript. But that's not your goal, right? Your end goal is to save your Html page as a pdf and send it through ajax. So you need to ask, is there any other way to save my Html page as pdf besides using window.print()? Now you are on the right track. To convert Html to pdf, you can use jsPDF's .html() PlugIn and html2canvas 1.0.0-alpha.12.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.debug.js"
integrity="sha384-NaWTHo/8YCBYJ59830LTz/P4aQZK1sS0SneOgAvhsIl3zBu8r9RevNg5lHCHAuQ/"
crossorigin="anonymous"></script>
<script src="~/lib/html2canvas/html2canvas.min.js"></script></script>
<!-- html2canvas 1.0.0-alpha.11 up to v1.0.0-rc.1 works, current version may not work -->
<script>
function emailHtml() {
let pdf = new jsPDF('p', 'pt', 'a4');
pdf.html(document.body, {
callback: function () {
let obj = {};
obj.pdfContent = pdf.output('datauristring');
var jsonData = JSON.stringify(obj);
$.ajax({
url: '/api/yourapi',
type: 'POST',
contentType: 'application/json',
data: jsonData
});
}
});
}
</script>

You cannot get a value from window.print().

Related

Ajax doesn't get a success response back after file upload

I just started with Ajax and also tried to find a solution for this.
Here is the problem:
I upload a .csv to a server. This works just fine. But after the upload "success" in the ajax call won't respond. Neither does complete or error. It shows nothing. Not even an empty alert. Just nothing. I also didn't find anything in the logs.
When I click the upload button without chosing a file to upload I get a response from success...
Here is the code:
upload.php
<?php
header('Content-type: application/json');
$target_dir = 'uploads/';
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$response[] ='';
if(move_uploaded_file($_FILES["file"]["tmp_name"],$target_file))
{
//$response['message'] = "File was uploaded!";
$response['message'] = csvToJson($target_file);
}
else
{
$response['message'] = 'Sorry, there was an error uploading your file.';
}
echo json_encode($response);
function csvToJson($file)
{
// open csv file
if (!($fp = fopen($file, 'r'))) {
die("Can't open file...");
}
//read csv headers
$key = fgetcsv($fp,"1024",";");
// parse csv rows into array
$json = array();
while ($row = fgetcsv($fp,"1024",";")) {
$json[] = array_combine($key, $row);
}
// release file handle
fclose($fp);
// encode array to json
return $json;
}
?>
upload.js
$(document).ready(function(e)
{
// Submit form data via Ajax
$("#form").on('submit', function(e)
{
e.preventDefault();
var form_data = new FormData($(this)[0]);
$.ajax({
type: 'POST',
url: 'upload.php',
data: form_data,
contentType: false,
cache: false,
processData:false,
success: function(response)
{
//var json = $.parseJSON(response)
alert(response);
},
error: function(error){
console.log("Error:");
console.log(error);
},
complete: function(response){
alert(response);
}
});
});
});
the form in index.php
<form id=form enctype="multipart/form-data">
<input type="file" name="file" id="file">
<input type="submit" value="Upload Excel" name="submit">
</form>
In the end I want a json back with the content of the uploaded file. But right now there is zero output if the file is uploaded.
Thanks for any advice!
EDIT for Solution:
The problem was something way different.
I had to format the output from csvToJson to UTF-8. After that I get a json as the respone.
Function for formatting to UTF-8 (got it from another post here)
function utf8ize($d) {
if (is_array($d)) {
foreach ($d as $k => $v) {
$d[$k] = utf8ize($v);
}
} else if (is_string ($d)) {
return utf8_encode($d);
}
return $d;
}
Solution, but cannot mark it:
The problem was something way different. I had to format the output from csvToJson() in upload.php to UTF-8. After that I get a json as the respone.
Function for formatting to UTF-8 (got it from another post here)
function utf8ize($d) {
if (is_array($d)) {
foreach ($d as $k => $v) {
$d[$k] = utf8ize($v);
}
} else if (is_string ($d)) {
return utf8_encode($d);
}
return $d;
}

Why is the input file data empty? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am working with an ajax PHP upload, the upload works well without ajax jQuery. I went to Google to find more resources on it and adjusted my code several times but still get the same error at the backend that file is empty. This is my code.
At the frontend
<input class="input is-link" id="file" name="file" type="file">
<button id="sendImg" class="button">Send</button>
</form>
My jQuery code
$(function(){
$("#chatsCard").on('click', '#sendImg', function (e){
e.preventDefault();
//alert("test");
var filedata = $("#file").prop("files")[0];
var recipient = $("#uname").html();
//alert(filedata);
$.ajax({
type:'post',
url:'upload.php',
contentType:false,
processData:false,
cache:false,
dataType:'json',
data:{
//rec:recipient,
filedata
},
success:function(data){
alert (data);
}
});//ajax end
});//click end
});//doc end
Backend
<?php
session_start();
require("assets/db.php");
$logged = $_SESSION['logged'];
//This is always my ajax response.
if(empty($_FILES['file'])){
$response = "No picture selected";
echo json_encode($response);
exit;
}
$imgFolder = "media/";
$fileTpath = $_FILES['file']['tmp_name'];
$fileSize = filesize($fileTpath);
$info = finfo_open(FILEINFO_MIME_TYPE);
$filetype = finfo_file($info, $fileTpath);
$filetype = explode ("/",$filetype);
$filetype = $filetype[1];
$allowedFiles = array("jpg" , "png" , "jpeg");
//rename image.
$newName = uniqid(8);
$newName = "recipient".
$newName. "." . $filetype;
//check file size
if($fileSize > 21464568){
$response = "Picture is greater than 2MB, Resize and try again";
echo json_encode($response);
exit;
}
//check format.
elseif(!in_array($filetype, $allowedFiles)){
$response= "You are only allowed to upload jpeg,jpg or png";
echo json_encode($response);
exit;
}
//check for existence of file.
elseif(file_exists($imgFolder.$newName)){
$response = "Failed!!! Upload again!!!";
echo json_encode($response);
exit;
}
//move to folder.
else{
move_uploaded_file($fileTpath,$imgFolder .$newName);
$recipient = $_POST['rec'];
$time = date("d-M-y")." at ". date("h:ia");
$msg = "media";
//insert to messaging
$q = "INSERT INTO messaging(message,sender, receiver,time) VALUES(?,?,?,?)";
$stm = $conn->prepare ($q);
$stm->bind_param("ssss",$msg,$logged,$recipient,$time);
$stm->execute();
//insert media details
$q1 = "INSERT INTO media(sender,mediaName,mediaType) VALUES(?,?,?)";
$stm = $conn->prepare ($q1);
$stm->bind_param("sss",$logged,$newName,$fileType);
$stm->execute();
//json response
$response = "success";
echo json_encode($response);
exit;
}
?>
Since I removed the jQuery and the uploading works normally, I assumed the problem is not from the backend so I focused on the jQuery by tweaking it to these
//First change
var fd = new FormData();
var file = $("#file").props('files')[0];
var file data= fd.append("file",filedata);
//This still gives no picture selected.
//Second change
var fd = new FormData($("#mediaPic")[0])
//Passed fd as data but still the same response.
//Tried other stuffs I got on Google to get the image data but still d same response.
You just need to post FormData() object, Append method returns null. Datatype text is preferred. So the final jQuery code would be:
$(function(){
$("#sendImg").on('click', function (e){
e.preventDefault();
//alert("test");
var recipient = $("#uname").html();
var form_data = new FormData();
var file = $("#file").prop('files')[0];
form_data.append('file', file);
$.ajax({
url: 'upload.php',
dataType: 'text',
type: 'post',
cache: false,
contentType: false,
processData: false,
data: form_data,
success: function(data) {
alert(data);
}
});//ajax end
});//click end
});//doc end
To add additional value with form_data, simple use before submitting
form_data.append("rec", "value");

PHP - Problem with fileupload (index.php->custom.js->function.php)

Hi Guys!
Im having isusses with my wordpress plugin. Im trying to upload a file through a form.
The problem is that I can't store my type="file" in the database.
I have some other functions where I put values like text inside my database without any problems.
I dont know if im supposed to change the custom.js function file or what to do...
Can u guys help me out?
thx for helping.
This is my Index.php
<form id="frmCreateFile" class="form-horizontal" action="javascript:void(0)" method="post"
enctype="multipart/form-data">
Select Image File to Upload:
<input id="file" type="file" name="file">
<input type="submit" name="submit" value="Upload">
</form>
This is my Custom.js
jQuery("#frmCreateFile").validate({
submitHandler:function(){
var postdata = jQuery("#frmCreateFile").serialize()+"&action=crm_request&param=create_file";
jQuery.post(crm_ajax_url, postdata, function(response){
var data = jQuery.parseJSON(response);
location.reload();
})
}
});
This is my Function.php
global $wpdb;
$param = isset($_REQUEST['param']) ? $_REQUEST['param'] : "";
if(!empty($param) && $param=='create_file'){
$customerId = '358';
// File upload path
$targetDir = VEOSOFT_CRM_DIR . "/uploads/";
echo $targetDir;
$fileName = basename($_FILES["file"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"])){
// Allow certain file formats
$allowTypes = array('jpg','png','jpeg','gif','pdf');
if(in_array($fileType, $allowTypes)){
// Upload file to server
if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
// Insert image file name into database
$insert = $wpdb->query("INSERT into wpwh_veosoft_crm_file (fileName, uploadDate, customer_Id) VALUES ('".$fileName."', NOW(),$customerId)");
if($insert){
$statusMsg = "The file ".$fileName. " has been uploaded successfully.";
}else{
$statusMsg = "File upload failed, please try again.";
}
}else{
$statusMsg = "Sorry, there was an error uploading your file.";
}
}else{
$statusMsg = 'Sorry, only JPG, JPEG, PNG, GIF, & PDF files are allowed to upload.';
}
}else{
$statusMsg = 'Please select a file to upload.';
}
}
After clicking on submit my database is inserting a new row in my table with this value:
Id = 51
FileName = (empty)
Date = 2019-12-17
You cannot upload file using normal Ajax or in key value pairs. Files are uploaded using Multipart data.
Please try following Javascript
jQuery("#frmCreateFile").validate({
submitHandler:function(){
var fd = new FormData();
var files = $('#file')[0].files[0];
fd.append('file',files);
$.ajax({
url: crm_ajax_url,
type: 'post',
data: fd+"&action=crm_request&param=create_file",
contentType: false,
processData: false,
success: function(response){
if(response != 0){
$("#img").attr("src",response);
$(".preview img").show(); // Display image element
}else{
alert('file not uploaded');
}
}
});
}
});

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

.ajax for upload file and send text input to php, showed error message but upload success

I know this is a simple questions for experts here, but it has been bothering me for a few days. I am a beginners, and I think there is some problem in handling the data.
So my purpose here is to both fetched the file uploaded and email input by user, send it to upload.php, and then upload.php will return a reference ID, and then display it to user.
The problem I faced is instead of alert me with the reference number, it will show two errors:
Undefined index fileToUpload in xampp/htdocs...
There is an error in uploading file
But, the upload file is successful, I can see the uploaded file in my database and reference code is generated successfully.
If this two issues are solve, how can I display the reference code in the HTML part. Thanks!!! Any help is appreciate!
<form id="main-contact-form" class="main-contact-form" name="main-contact-form" method="post" enctype="multipart/form-data">
<div class="form-group">
<input type="email" name="email" class="form-control" required="required" placeholder="Email Address">
<input type="file" name="fileToUpload" id="fileToUpload" value="fileToUpload">
<input type="submit" value="submit" name="submit" class="btn btn-primary pull-left crsa-selected">
</div>
</form>
Here is my .ajax call that going to send email address and uploaded file to upload.php
$(document).ready(function () {
$("#main-contact-form").on('submit',(function(e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: 'upload.php',
type: 'post',
data: formData,
cache: false,
contentType: false,
processData: false,
async: false,
success: function()
{
alert("ajax success");
}
});
function reqListener () {
console.log(this.responseText);
}
var oReq = new XMLHttpRequest();
oReq.onload = function() {
alert(this.responseText);
};
oReq.open("get", "upload.php", true);
oReq.send();
}));
});
This is my upload.php
<?php
include("db.php");
$target_dir = "";
$target_file = "";
$target_dir = "submittedform/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$refId = "";
// upload file
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file))
{
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded. <br/>";
$refID = !empty($_POST['refID']) ? $_POST['refID'] : time() . rand(10*45, 100*98);;
// echo "Reference ID: " . $refID . "<br/>";
echo json_encode("Reference ID: " . $refID . "<br/>");
#once file uploaded, the path and reference code will be updated, status will be set to 1
$sqlInsert = "INSERT INTO student(reference_id, upload_appli_form, status) VALUES ('$refID', '$target_file', '1')";
$qInsert = mysqli_query($db, $sqlInsert) or die("Error : ". mysqli_error($qInsert));
}
else
{
echo json_encode("Sorry, there was an error uploading your file. <br/>");
}
mysqli_close($db);
?>
Maybe it must be simpler? Like this?
And now it's async. So it will be valid for years :D
$(document).ready(function () {
$("#main-contact-form").on('submit', (function(e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: 'upload.php',
type: 'post',
data: formData,
cache: false,
contentType: false,
processData: false
}).done(function(result) {
alert(result); //your POST answer
});
}));
});

Categories