I have list of html stored in database, I want to retrieve the data and convert it to pdf and after converting download it with via ajax request.
I tried hands on it but when the pdf get download the downloaded file is empty.
Please what do i need to do?
Thank you.
JS Code
SMSLiTe('click','.export-to-pdf',function(event){
event.preventDefault();
///export note to pdf via ajax
if (typeof notes[0].note.nid !== typeof undefined && notes.length) {
var nid = notes[0].note.nid;
var fd = new FormData();
fd.append('export_to_pdf',true);
fd.append('note_id',nid);
request.open(bigPipe.formMethod.a, 'pdf/pdf');
request.send(fd);
request.onload = function(e){
if (request.readyState == request.DONE && request.status ==200) {
//code here ....download
var data = request.responseText,
blob = new Blob([data]),
a = document.createElement('a'), d = new Date();
a.href = window.URL.createObjectURL(blob);
a.download = d.getTime()+'.pdf'; a.click();
}
}
}else{
sustainScroll(bigPipe.c_w,bigPipe.class.fixed);
var msg = 'Sorry! something gone wrong, please refresh this page and try again.',title = 'Export Failed';
$(bigPipe.document).append(flexibleDialog({content:templateHTML.flexDialog(msg,title,'_2d0',null,'Close',null,0),isClass:'export_to_pdf_failed _2d0',heigt:140,width:600}));jkg();
}
});
PHP Code
if (isset($_POST['note_id'],$_POST['export_to_pdf'])) {
$nid = (int)$_POST['note_id'];
$sql = "SELECT content FROM $notes_table WHERE note_id='{$nid}' LIMIT 1";
$query = mysqli_query($conn,$sql);
if (mysqli_num_rows($query)) {
$row = mysqli_fetch_assoc($query);
$content = $row['content'];
//create PDF file
$mpdf = new mPDF();
$mpdf->WriteHTML($content);
$mpdf->Output(time().'.pdf','D');exit;
}
}
Inspecting the response data returning from MPDF I realized the output data was a blob and since the data was already blob data. I had a clue of changing the responseType of XMLHttpRequest.responseType to blob
and it worked for now.
modified JS:
SMSLiTe('click','.export-to-pdf',function(event){
event.preventDefault();
//set request method
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
var request = new XMLHttpRequest();
} else { // code for IE6, IE5
var request = new ActiveXObject("Microsoft.XMLHTTP");
}
///export note to pdf via ajax
if (typeof notes[0].note.nid !== typeof undefined && notes.length) {
var nid = notes[0].note.nid;
var fd = new FormData();
fd.append('export_to_pdf',true);
fd.append('note_id',nid);
request.open(bigPipe.formMethod.a, 'pdf/pdf');
request.send(fd);
request.responseType = 'blob';//change reponseType before onload
request.onload = function(e){
if (request.readyState == request.DONE && request.status ==200) {
//code here ....download
var data = request.response,
blob = new Blob([data],{type: 'application/pdf'}),
a = document.createElement('a'), d = new Date();
a.href = window.URL.createObjectURL(blob);
a.download = d.getTime()+'.pdf'; a.click();
//console.log(data);
}
}
}else{
sustainScroll(bigPipe.c_w,bigPipe.class.fixed);
var msg = 'Sorry! something gone wrong, please refresh this page and try again.',title = 'Export Failed';
$(bigPipe.document).append(flexibleDialog({content:templateHTML.flexDialog(msg,title,'_2d0',null,'Close',null,0),isClass:'export_to_pdf_failed _2d0',heigt:140,width:600}));jkg();
}
});
PHP Code:
We have to output MPDF as string since we're not appending MPDF to browser;
//create PDF file
$mpdf = new mPDF();
$mpdf->WriteHTML($content);
$output = $mpdf->Output(time().'.pdf','S');//output as string
echo($output); //final result to JS as blob data
Related
I am generating a CSV string with PHP and send it via AJAX to my Javascript function.
A simple button
<button id="download" type="button" onclick="csvExport()" name="button">CSV</button>
Call that function and should download a CSV file from the string. How can I handle that?
My PHP Function
function exportCSV(){
$profs = $this->getAllDozent();
$profs = json_decode($profs, true);
$currentID = 0;
$csv = "IDDOZENT,IDVERANSTALTUNG,BEZEICHNUNG,SWS,CREDITS,HAEUFIGKEIT_PA,FAKTOR_DOPPELUNG,SOMMER,WPF,KOSTEN_PA,\n";
// Iteriere durch Professor Array
foreach($profs as $key => $value){
$currentID = $value['IDDOZENT'];
//Hole für ID die Veranstaltungen
$veranstaltungen = $this->getVeranstaltungenByID($currentID);
$veranstaltungen = json_decode($veranstaltungen, true);
//Nur wenn Veranstaltungen da sind, abrufen.
if($veranstaltungen != "NULL"){
foreach ($veranstaltungen as $key => $value) {
$csv = $csv.$currentID.","
.$value['IDVERANSTALTUNG'].","
.$value['BEZEICHNUNG'].","
.$value['SWS'].","
.$value['CREDITS'].","
.$value['HAEUFIGKEIT_PA'].","
.$value['FAKTOR_DOPPELUNG'].","
.$value['SOMMER'].","
.$value['WPF'].","
.$value['KOSTEN_PA']."\n";
}
}
}
return $csv;
}
returns a valid csv string like that "a,b,c,d".
My Javascript looks like:
function csvExport(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200){
console.log(this.responseText);
}
};
xmlhttp.open("GET", "csvExport.php", true);
xmlhttp.send();
}
In the callback, I want to download the this.responseText as a CSV file. Is that possible?
Instead of console.log in ajax onreadystatechange handler call this function
function downloadAsFile(csv, fileName) {
var file = new File([csv], fileName, { type: "text/csv" })
var anUrl = window.URL.createObjectURL(file)
var a = window.document.createElement('a');
a.href = window.URL.createObjectURL(file)
a.download = fileName;
a.click();
}
i am using javascript to upload an image using the unsigned mode. the resultant image is a blank image or i can say an image filled with black color. not sure what is wrong. the code looks like follow:
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "https://api.cloudinary.com/v1_1/mycloud/image/upload", false);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.onreadystatechange = function() { //Call a function when the state changes.
if (xhttp.readyState == 4 && xhttp.status == 200) {
alert(xhttp.responseText);
} else {
alert("Error dude: " + xhttp.statusText);
}
}
var parameters = {
"file": imgData,
"upload_preset": "mycode"
};
xhttp.send(JSON.stringify(parameters));
resultant image is:
http://res.cloudinary.com/viksphotography/image/upload/v1490752341/irgvt7b3qwoug1vz7own.jpg
Please note that imgData is base64 encoded
You need to use FormData for uploading the file:
const cloudName = 'your cloud name';
const unsignedUploadPreset = 'your unsigned upload preset';
// Upload base64 encoded file to Cloudinary
uploadFile('data:image/gif;base64,R0lGODlhSAFIAf....');
// *********** Upload file to Cloudinary ******************** //
function uploadFile(file) {
var url = `https://api.cloudinary.com/v1_1/${cloudName}/upload`;
var xhr = new XMLHttpRequest();
var fd = new FormData();
xhr.open('POST', url, true);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onreadystatechange = function(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
// File uploaded successfully
var response = JSON.parse(xhr.responseText);
// https://res.cloudinary.com/cloudName/image/upload/v1483481128/public_id.jpg
var url = response.secure_url;
// Create a thumbnail of the uploaded image, with 150px width
var tokens = url.split('/');
tokens.splice(-2, 0, 'w_150,c_scale');
var img = new Image(); // HTML5 Constructor
img.src = tokens.join('/');
img.alt = response.public_id;
document.body.appendChild(img);
}
};
fd.append('upload_preset', unsignedUploadPreset);
fd.append('tags', 'browser_upload'); // Optional - add tag for image admin in Cloudinary
fd.append('file', file);
xhr.send(fd);
}
See full example here. It will upload a small Michael Jordan jumpman image to your account.
I am trying to send a user uploaded text file via an XMLHttpRequest with the following code:
HTML
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
Javascript
function Upload_Text()
{
var file = document.getElementById("file").files[0];
var table_type = 2;
if (document.myform.Table_Name_Text[0].checked == true) {table_type = 1;}
var Choose_Class = document.getElementById("Choose_Class").value;
var formData = new FormData();
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var result = xmlhttp.responseText;
alert(result);
}
}
var url = "Upload_Text.php";
url = url + "?table_type="+table_type;
url = url + "&Choose_Class="+Choose_Class;
formData.append("thefile", file);
xmlhttp.open('POST', url, true);
xmlhttp.send(formData);
}
However with the following PHP code, I do not receive any data from the text file server side.
<?php
$file = $_FILES['thefile'];
$table_type=$_REQUEST["table_type"];
$Choose_Class=$_REQUEST["Choose_Class"];
$fh = fopen($file, 'r');
$theData = fread($fh, filesize($file));
fclose($fh);
echo $theData;
?>
Any help with this would be great, thanks.
Try adding ["tmp_name"] to the file string. So: $file = $_FILES['thefile']['tmp_name'];
This will get the file's temporary location. Looking through your code everything else seems fine.
I want to replicate some functionality from Digg.com whereby when you post a new address it automatically scans the url and finds the page title.
I am programming in classic ASP and VBScript and using javascript. Anyone know a script to make this happen..?
Many thanks in advance..
Paul
This is somewhat of a rudimentary example. You should probably include some data verification.
The ASP page should be called something like getPageTitle.asp
<%
Response.Buffer = True
Dim strURL, objXMLHTTP, objXML, strContents
Dim objRegExp, strHTML, strPattern, colMatches, strTitle
strURL = Request.Form("url")
Set objXMLHTTP = Server.CreateObject ("Microsoft.XMLHTTP")
'Or if this doesn't work then try :
'Set objXMLHTTP = Server.CreateObject("MSXML2.ServerXMLHTTP")
objXMLHTTP.Open "GET", strURL, False
objXMLHTTP.Send
strContents = objXMLHTTP.ResponseText
Set objXMLHTTP = Nothing
Set objRegExp = New RegExp
strPattern = "<title>(.*?)<\/title>"
objRegExp.Pattern = strPattern
objRegExp.IgnoreCase = True
objRegExp.Global = True
Set colMatches = objRegExp.Execute(strContents)
If colMatches.Count > 0 then
strTitle = objMatches(0).Value
Else
strTitle = ""
End If
Set objRegExp = Nothing
Response.write(strTitle)
%>
This is a basic JavaScript POST implementation. You could spruce this up a bit with any JS framework you like.
var script = "http://www.example.com/getPageTitle.asp"
var page2check = "http://www.example.com/somePageToCheck.html"
function getXMLHttpRequestObject() {
var xmlhttp;
/*#cc_on
#if (#_jscript_version >= 5)
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
#else
xmlhttp = false;
#end #*/
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
var http = new getXMLHttpRequestObject();
var parameters = "url="+page2check;
http.open("POST", script, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", parameters .length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {
if(http.readyState == 4) {
alert(http.responseText);
}
}
http.send(parameters);
var pageTitle = http.ResponseText
I hope this helps.
Send url from clientside to serverside using javascript(ajax).
Load html page by it's url using asp on serverside.
Parse html page, extract title.
Send title to clientside.
I am trying to create a google-chrome-extension that will download an mp3 file. I am trying to use HTML5 blobs and an iframe to trigger a download, but it doesn't seem to be working. Here is my code:
var finalURL = "server1.example.com/u25561664/audio/120774.mp3";
var xhr = new XMLHttpRequest();
xhr.open("GET", finalURL, true);
xhr.setRequestHeader('Content-Type', 'application/octet-stream');
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 200)
{
var bb = new (window.BlobBuilder || window.WebKitBlobBuilder)();
bb.append(xhr.responseText);
var blob = bb.getBlob("application/octet-stream");
var saveas = document.createElement("iframe");
saveas.style.display = "none";
saveas.src = window.webkitURL.createObjectURL(blob);
document.body.appendChild(saveas);
delete xhr;
delete blob;
delete bb;
}
}
xhr.send();
When looked in the console, the blob is created correctly, the settings look right:
size: 15312172
type: "application/octet-stream"
However, when I try the link created by the createObjectURL(),
blob:chrome-extension://dkhkkcnjlmfnnmaobedahgcljonancbe/b6c2e829-c811-4239-bd06-8506a67cab04
I get a blank document and a warning saying
Resource interpreted as Document but
transferred with MIME type
application/octet-stream.
How can get my code to download the file correctly?
The below code worked for me in Google chrome 14.0.835.163:
var finalURL = "http://localhost/Music/123a4.mp3";
var xhr = new XMLHttpRequest();
xhr.overrideMimeType("application/octet-stream");
//xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.open("GET", finalURL, true);
xhr.responseType = "arraybuffer";
xhr.onload = function() {
var bb = new (window.BlobBuilder || window.WebKitBlobBuilder)();
var res = xhr.response;
if (res){
var byteArray = new Uint8Array(res);
}
bb.append(byteArray.buffer);
var blob = bb.getBlob("application/octet-stream");
var iframe = document.createElement("iframe");
iframe.style.display = "none";
iframe.src = window.webkitURL.createObjectURL(blob);
document.body.appendChild(iframe);
};
xhr.send(null);
I'm not sure, but i think this is your server's trouble. I've just tried your piece of code to download some sample blob of mp3-file and everything went ok. So maybe:
this file doesn't exist on your server
you server outputs wrong mime type for mp3 files