I am struggling to perform an XSLT transform in the browser using just html and javascript (I have tried many different ways and none of them work). Here is what I want (and I just can't make it work).
1) I have an XSLT transform, I can make it available as a file (e.g. xslt), I can embed it in the HTML (I don't care), it is static.
2) I want the user to enter their XML into a text area.
3) I want the user to press a button and then I want the XSLT to occur and the result (which is html) to be displayed in a new tab.
Thanks for your help.
Finally got my own javascript to work. Here it is for anyone who needs it.
/**
* Load an XML document from server
*
* #param filename filename
*
* #return DOMDocument
*/
function loadXMLDoc(filename) {
if ((window.ActiveXObject) || (!(window.ActiveXObject) && "ActiveXObject" in window)) {
xhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
else {
xhttp = new XMLHttpRequest();
}
xhttp.open("GET", filename, false);
try {
xhttp.responseType = "msxml-document"
}
catch (err) { } // Helping IE11
xhttp.send("");
return xhttp.responseXML;
}
/**
* Text XML template: perform XSLT on user XML
*
*/
function testXMLTemplate() {
// create xml string from user xml in text area
var xmlstr = document.getElementById("test-xml").value;
xmlstr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + xmlstr;
// load XSLT doc
var xsldoc = loadXMLDoc("xml/paramToHtml.xslt")
if ((window.ActiveXObject) || (!(window.ActiveXObject) && "ActiveXObject" in window)) {
// code for IE
var xmldoc = new ActiveXObject("Msxml2.DOMDocument.3.0");
xmldoc.async = false;
xmldoc.loadXML(xmlstr);
ex = xmldoc.transformNode(xsldoc);
var xmlTestWin = window.open();
xmlTestWin.document.write(ex);
}
else if (document.implementation && document.implementation.createDocument) {
// code for Chrome, Firefox, Opera, etc.
var xmlparser = new DOMParser();
var xmldoc = xmlparser.parseFromString(xmlstr, "text/xml");
xsltProcessor = new XSLTProcessor();
xsltProcessor.importStylesheet(xsldoc);
resultDocument = xsltProcessor.transformToDocument(xmldoc);
var xmlTestWin = window.open();
xmlTestWin.document.write(resultDocument.firstChild.innerHTML);
}
}
Related
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
Recently I was facing an issue while loading an xml in IE11.So I went through different links and solved the issue and now the xml is getting loaded but multiple blank rows are appearing.
I do not have any clue how this issue can be solved.
I am providing below the code which I am using to load the xml in IE11 and also the screenshot with multiple blank rows:
Code:
function loadXMLDoc(fname)
{
var xmlDoc;
var nVer = navigator.appVersion;
var nAgt = navigator.userAgent;
var nameOffset, verOffset, ix;
// code for IE
if (window.ActiveXObject!=="undefined")
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
}
if ((verOffset = nAgt.indexOf("Chrome")) == -1 || (verOffset = nAgt.indexOf("Safari")) == -1)
{
xmlDoc.async = false;
xmlDoc.load(fname);
return(xmlDoc);
}
}
function displayResult(xmlData)
{
xml = loadXMLDoc(xmlData);
xsl = loadXMLDoc("finalsheet.xsl");
// code for IE
if (window.ActiveXObject!=="undefined")
{
ex = xml.transformNode(xsl);
return ex;
}
Here is a screenshot of the issue, XML is getting displayed with multiple blank rows above and below the data
i am trying to upload an xml file using javascript. my javascript code is given below:
var xmlDoc =null;
var abc = new Array();
if (window.ActiveXObject){
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
}
else if (document.implementation.createDocument){
xmlDoc=document.implementation.createDocument("","",null);
}
else{
alert('Browser cannot handle this script');
}
if (xmlDoc!=null){
xmlDoc.async=false;
xmlDoc.load("employee.xml");
var x = xmlDoc.getElementsByTagName("EMP");
for (i=0;i<x.length;i++)
{
abc[0] = x[0].getElementsByTagName("ID")[0].childNodes[0].nodeValue;
document.write("a is "+abc[0]);
abc[1] = x[0].getElementsByTagName("ID1")[0].childNodes[0].nodeValue;
document.write("<br>b is "+abc[1]);
}
}
and my xml file is:
<EMPLOYEE>
<EMP>
<ID>10.99</ID>
<ID1>20.54</ID1>
</EMP>
</EMPLOYEE>
the code is working properly in IE as well as firefox but in Google Chrome, it is not showing anything. can some one tell me where i am wrong or how to correct it.
In order to get the XML file in Chrome you need to execute a GET. For security reasons you cannot load it in a straight forward manner from the file system. Here's code:
var xmlhttp = new window.XMLHttpRequest();
xmlhttp.open("GET", xmlsrc, false);
xmlhttp.send(null);
var xmlDoc = xmlhttp.responseXML.documentElement;
Hello I am new to the community. I would like to ask a question.
I am trying to create a template HTML5 for loading and doing quizzes. I have the xml file with the question and the answers and I am trying to load it, in my template.
The code I use is this:
To load the xml file
// The Script that loads the XML File Locally only works in Firefox for now
function loadXMLDoc(XMLname) {
var xmlDoc;
if (window.XMLHttpRequest) {
xmlDoc = new window.XMLHttpRequest();
xmlDoc.open("GET", XMLname, false);
xmlDoc.send("");
return xmlDoc.responseXML;
}
// IE 5 and IE 6
else if (ActiveXObject("Microsoft.XMLDOM")) {
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.load(XMLname);
return xmlDoc;
}
else {
xmlhttp = new XMLHttpRequest();
//Open the file using the GET routine
xmlhttp.open("GET", XMLname, false);
//Send request
xmlhttp.send(null);
//xmlDoc holds the document information now
return xmlDoc.responseXML;
}
alert("Error loading document!");
return null;
}
To Pass the Contents to my HTML5 template
xmlDoc=loadXMLDoc("test"+file+".qxml");
My problem is that the data from the xmlfile are not retrieved. While on the server or on any other browser the xmlDoc variable appears as null.
Can you point me in some direction as I am new to the Javascript xmlhttprequest methods. Thanks a lot in advance for your time.
The file extension is not xml (it is .qxml). The problem is the extension of the file .qxml. So it there any way to bypass this and use my extension qxml instead of xml ?
Try to override the mime type returned by the server, and tell your browser that the data is XML.
// The Script that loads the XML File Locally only works in Firefox for now
function loadXMLDoc(XMLname) {
var xmlDoc;
if (window.XMLHttpRequest) {
xmlDoc = new window.XMLHttpRequest();
xmlDoc.open("GET", XMLname, false);
xmlDoc.overrideMimeType('text/xml');
xmlDoc.send("");
return xmlDoc.responseXML;
}
// IE 5 and IE 6
else if (ActiveXObject("Microsoft.XMLDOM")) {
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.load(XMLname);
return xmlDoc;
}
else {
xmlhttp = new XMLHttpRequest();
//Open the file using the GET routine
xmlhttp.open("GET", XMLname, false);
xmlhttp.overrideMimeType('text/xml');
//Send request
xmlhttp.send(null);
//xmlDoc holds the document information now
return xmlDoc.responseXML;
}
alert("Error loading document!");
return null;
}
Given the following code (and not using jQuery)
what would be a good way to dynamically insert an tag into the xsl before transformation? I would like someone to "fix" function addParam
function addParam(xsl,name,value) {
/** input:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">.....
output:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:param name="parm1" value="parameter number 1" />
<xsl:template match="/">.....
*/
var parameter = document.createElement("xsl:param");
parameter.setAttribute("name",name);
parameter.setAttribute("value",value);
xsl.documentElement.insertBefore(parameter,xsl.documentElement.firstsChild)
}
function displayResult(pXml) {
var xsl = loadXMLDoc("cdcatalog.xsl");
// code for IE
if (window.ActiveXObject) {
/* I want to call it here >>> */
addParam(xsl,"parm1","parameter value1");
var ex = pXml.transformNode(xsl);
document.getElementById("availableSearchItems").innerHTML = ex;
}
// code for Mozilla, Firefox, Opera, Chrome, etc.
else if (document.implementation && document.implementation.createDocument) {
xsltProcessor = new XSLTProcessor();
xsltProcessor.importStylesheet(xsl);
/* I want to call it here */
addParam(xsl,"parm1","parameter value1");
resultDocument = xsltProcessor.transformToFragment(pXml, document);
document.getElementById('availableSearchItems').innerHTML = "";
document.getElementById("availableSearchItems").appendChild(resultDocument);
}
}
I have read how to pass a parameter from an URL to a XSL stylesheet using jQuery? and understand that Firefox can do setParameter and IE can do
var strParam = "//xsl:param[#name='" + p + "']";
var xslParam = xObj.selectSingleNode(strParam);
xslParam.setAttribute("select",op[p]);
but that is assuming the xsl has a parameter already.
Pointers and corrections very welcome.
Thanks
Why do you want to change the parameter name in the xsl ? Surely that could be static and you change what the value of that parameter is? You could then set what you want to pass into the xsl in the JavaScript and do it that way and its easy.
<xsl:param name="parm1"/>
Then that gets a value when you call the add and set parameter functions as show below. You could even test to make sure its not null before passing it through.
//code for ie
if (window.ActiveXObject)
{
var xslt = new ActiveXObject("MSXML2.FreeThreadedDOMDocument");
xslt.async = false;
xslt.load(xsl);
var template = new ActiveXObject("MSXML2.XSLTemplate");
template.stylesheet = xslt;
var process = template.createProcessor();
process.input = xml;
if(yourparam != ""){
process.addParameter("paramID", yourparam);
}
process.transform();
}
// code for Mozilla, Firefox, Opera, etc.
else if (document.implementation && document.implementation.createDocument)
{
var xml_serializer = new XMLSerializer();
xsltProcessor=new XSLTProcessor();
xsltProcessor.importStylesheet(xsl);
if(yourparam != ""){
xsltProcessor.setParameter(null, "paramID", yourparam);
}
}