I have a complex table generated via javascript that I'd like to save as PDF on the server. I've looked around at the pdf generation libraries and they all seem to be limited in terms of style, fonts, etc (that's what I meant by 'complex'). The table can be download client side as PDF or printed.
Let's say my function that generates the form to be printed is reportBody(data); - is there a way I can use AJAX to send the document as PDF to a php file that will save it server-side instead of downloading it client-side? The reportBody(data) is a collection of other variables, function calls etc.
So basically the question is - since we can generate a PDF file client-side, can we POST it (the pdf) via ajax to the server?
Short answer is Yes. Your provided information is still limited as it's not clear what is ran in the reporBody(data) but most PDF libraries on client side are able to give you the PDF file as base64 encoded data in form of a string.
You can then simply send that string to the server and save that as a PDF file.
A simple implementation will be something like this:
// I have used jQuery for convenience but you can use any lib or Vanilla JS
var saveData = $.ajax({
type: 'POST',
url: "url-to-the-php-script",
data: { pdfData: 'base64StringDataHere'},
dataType: "JSON",
success: function(resultData) { alert("Save Complete") }
});
Then on server side, do something like this:
$pdfData= $_POST['pdfData'];
file_put_contents('filename.pdf', base64_decode($pdfData));
Yes, there are a lot of ways. One would be, if you have html code in your reportBody(data); you could:
Send the html to a php file via ajax
in this php you could use https://wkhtmltopdf.org/ to generate a pdf file
In the client side you could point to that pdf generated
Related
I would like to save uploaded file using javascript, in my linux server. The code I wrote is:
if (uploadInput.files.length == 0) {
console.log("No file is uploaded. ");
} else {
console.log("File uploaded.");
var file = uploadInput.files[0];
}
Now I would like to save that file as "files/upload.csv". Can anyone please advise, how can I do it?
Thanks in advance
What I'm going to do is walk you through the logic, instead of providing code. There is just not enough information here on what you want to do to provide actual code and the sample you provided is a very small part of what the actual solution would need to include.
I'm assuming the code you wrote above is meant to run on a website visitor's browser (client-side). Client-side code can't save to a server. What it can do, is send the file contents to the server. But then you'd need something on the server side to process that file contents and actually save it to the server-side files directory.
One method to send the file contents from the client to the server is to use AJAX - you can do this with native javascript, but I would recommend looking into a library such as Jquery, which makes it a lot easier. See http://api.jquery.com/jquery.ajax/ This AJAX code will need a communication point on the server to send the file contents to. From your profile it seems you're familiar with PHP. You could make a php file on the server (say receivefilecontents.php) that takes in input from that client-side AJAX call, and then saves it to a server directory - you could also do this in Python, Java or a number of other languages.
Is it possible to set a variable in JavaScript to a local JSON file stored on computer?
var data = c/path/path/data.json
If you are asking if you can access the file system with JavaScript the answer is yes and no. If you are using a tool like node.js then yes you can access the file system using JavaScript. If you are trying to access the file system from the browser then no JavaScript does not natively have that capability.
It really does not matter what you are trying to access on the file system. It could be JSON, jpg, or gif... If you are using a browser it is not possible..
However you can make ajax call to a server and get files that way. i.e. JSON files... You can also store information using JavaScript using the 'localstorage' method built into JavaScript.
You can make an Ajax request to get the external json.
$.ajax({
url: "c/path/path/data.json",
}).done(function(JsonToGet) {
var data = JsonToGet;
//Management of the JSON with 'data' variable.
});
I've found a mound of questions on SO regarding uploading a file using AJAX although none of them really seem to find my needs.
What I need to do is have a user upload an XML file and have the script run through the XML file and take out the data that is in certain tags in the file and then push the data into a corresponding array which reflects the tag. So say I found a book in an xml, it would push the data into an array NewBooks.
I don't have any experience with PHP, quite honestly its confusing to me. If there is a way without PHP, that would be grand.
reader.onload = function (e) {
console.log('reading file')
$(document).ready(function () {
console.log('analyzing ajax')
$.ajax({
type: "GET",
dataType: "xml",
success: function (xml) {
$(xml).find('book').each(function () {
UploadBooks.push($(this).text());
});
}
})
})
console.log(UploadBooks);
}
That is the code I have although the printed UploadBooks has no elements, even though when I look into the XML file, there are clearly book tags.
Not all browsers can upload files via Ajax. Only those supporting XMLHttpRequest2. Getting that to work with jQuery (as per your example) is going to take some tricks too.
You say you'd rather not use PHP, which would mean no point uploading a file anyway. Check out the HTML5 FileReader API if you want to try and parse the XML file on the client side. You might be able to load the file into a DOM structure to achieve what you're trying to do.
In our application we need to implement following scenario:
A request is send from client
Server handles the request and generates file
Server returns file in response
Client browser displays file download popup dialog and allows user to download the file
Our application is ajax based application, so it would be very easy and convenient for us to send ajax request (like using jquery.ajax() function).
But after googilng, it turned out that file downloading is possible only when using non-ajax POST request (like described in this popular SO thread). So we needed to implement uglier and more complex solution that required building HTML structure of form with nested hidden fields.
Could someone explain in simple words why is that ajax requests cannot be used to download file? What's the mechanics behind that?
It's not about AJAX. You can download a file with AJAX, of course. However the file will be kept in memory, i.e. you cannot save file to disk. This is because JavaScript cannot interact with disk. That would be a serious security issue and it is blocked in all major browsers.
This can be done using the new HTML5 feature called Blob. There is a library FileSaver.js that can be utilized as a wrapper on top of that feature.
That's the same question I'd asked myself two days ago. There was a project with client written using ExtJS and server side realisation was on ASP.Net. I have to translate server side to Java. There was a function to download an XML file, that server generates after Ajax request from the client. We all know, that it's impossible to download file after Ajax request, just to store it in memory. But ... in the original application browser shows usual dialog with options open, save and cancel downloading. ASP.Net somehow changed the standard behaviour... It takes me two day to to prove again - there is no way to download file by request usual way ... the only exception is ASP.Net... Here is ASP.Net code
public static void WriteFileToResponse(byte[] fileData, string fileName)
{
var response = HttpContext.Current.Response;
var returnFilename = Path.GetFileName(fileName);
var headerValue = String.Format("attachment; filename={0}",
HttpUtility.UrlPathEncode(
String.IsNullOrEmpty(returnFilename)
? "attachment" : returnFilename));
response.AddHeader("content-disposition", headerValue);
response.ContentType = "application/octet-stream";
response.AddHeader("Pragma", "public");
var utf8 = Encoding.UTF8;
response.Charset = utf8.HeaderName;
response.ContentEncoding = utf8;
response.Flush();
response.BinaryWrite(fileData);
response.Flush();
response.Close();
}
This method was called from WebMethod, that, in turn, was called from ExtJS.Ajax.request. That's the magic. What's to me, I've ended with servlet and hidden iframe...
you can do this by using hidden iframe in your download page
just set the src of the hidden ifame in your ajax success responce and your task is done...
$.ajax({
type: 'GET',
url: './page.php',
data: $("#myform").serialize(),
success: function (data) {
$("#middle").attr('src','url');
},
});
I develop a javascript application which display data from xml with charts and lists.
For now I put some sample files onto the server's directory that I load with :
$.ajax({ type: 'GET', url: 'data/default.xml', dataType: 'xml', ...})
The Xml files can be very heavy so when one of them is loaded I put the data in an IndexedDB.
In a second time I would like to let the visitor loads its own xml file by giving the filepath of the xml (f.i. : /home/user/sample.xml). I do not want to upload this file onto the server because I do not need it and it could be too big. But I do want to load those data in the IndexedDB and let the app displays data without any call to the server.
I do not know if browsers could work this way?
If they could, how can I do such a trick?
You can't use Ajax to get data from a file on the client system, but in sufficiently modern browsers you can use the File API. MDN has a guide to the File API that is friendlier then the specification.