Hello is a possible to get background-image url from different page with ajax?
I tried this but it seems that does not work. Thank you for help.
var test = jQuery('#el').load('https://www.example.com/somepage/' .some-element).css('background-image');
console.log(test);
or
jQuery.ajax({
url: 'https://www.example.com/somepage/',
type: 'get',
dataType: 'text',
success: function(data, status) {
console.log("Status: "+status+"\nData: "+data);
result = data;
var img = jQuery('.some-element').css('background-image');
console.log(img);
}
});
Both is same. How to get background-image url from another page with javascript?
Its not ajax but its solution what u proably need.
function loadBackground(url, query) {
return new Promise(function (resolve, reject) {
var iframe = document.createElement("iframe");
iframe.onload = function () {
var el = iframe.contentDocument.querySelector(query);
if (el) {
var style = iframe.contentWindow.getComputedStyle(el);
resolve(style.getPropertyValue("background-image"));
} else {
reject(new Error("Element not found"));
}
document.body.removeChild(iframe);
};
iframe.style.width = 0;
iframe.style.height = 0;
iframe.style.border = 0;
iframe.src = url;
document.body.appendChild(iframe);
});
}
loadBackground("https://www.example.com/somepage/", ".some-element").then(function (bg) {
console.log(bg);
});
I have this java script code that generate organizational chart from database
<script type="text/javascript">
google.load("visualization", "1", { packages: ["orgchart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
$.ajax({
type: "POST",
url: "add org unit.aspx/GetChartData",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Entity');
data.addColumn('string', 'ParentEntity');
data.addColumn('string', 'ToolTip');
for (var i = 0; i < r.d.length; i++) {
var employeeId = r.d[i][0].toString();
var employeeName = r.d[i][1];
var designation = r.d[i][2];
var reportingManager = r.d[i][3] != null ? r.d[
i][3].toString() : '';
data.addRows([[{
v: employeeId,
f: '<a target="_blank" href="edit emp cv.aspx?employeeId='+employeeId+'">' + employeeName + '</a>' + '<div><span>' + designation + '</div></span>',
}, reportingManager, designation]]);
}
var chart = new google.visualization.OrgChart($("#chart")[0]);
chart.draw(data, { allowHtml: true });
},
failure: function (r) {
alert(r.d);
},
error: function (r) {
alert(r.d);
}
});
}
</script>
and these web method in c# code behind
[WebMethod]
public static List<object> GetChartData()
{
DataLayer.StoreDBEntities dbEntities = new DataLayer.StoreDBEntities();
List<object> chartData = new List<object>();
List<DataLayer.org_unit> result = dbEntities.org_unit.ToList();
foreach (DataLayer.org_unit unit in result)
{
string name = unit.org_unit_type.alias + " " + unit.name;
string Details = "";
if (unit.emp_assignment.ToArray().Length != 0)
{
List<DataLayer.emp_assignment> empAssigns = unit.emp_assignment.ToList();
foreach (DataLayer.emp_assignment assign in empAssigns)
{
Details += assign.job_title.alias + ":" + assign.employee.name + "<br/>";
}
}
chartData.Add(new object[] { unit.id, name, Details, unit.upper_unit_id });
}
return chartData;
}
the chart is regenerated every postback and when page is load
although I did not call java script function at all
how to stop this ? i want to generate chart only whene butten click
First, you need to remove this google.setOnLoadCallback(drawChart); then you can use the jQuery click event like this:
$(function() {
$('#draw-chart').click(function(event) {
event.preventDefault();
drawChart();
});
});
Add a button to your HTML like this:
<button id="draw-chart">Draw Chart</button>
I'm not a massive javascript/jquery user but I've started to get more into it for use in mobile apps... I've been looking for an answer to solve my problem of getting a blank page when trying to output html as a pdf using jspdf and every post I find has something to do with blobs.
this is my code I have that exports a blank pdf I have left the pdf.save in so I get an export on my PC as a sample of what it should look like but on my ipad and nexus 7 it saves a blank pdf.
var pdf = new jsPDF('p', 'pt', 'letter'), source = $('#home')[0], specialElementHandlers = {
'#bypassme': function(element, renderer){
return true
}
}
margins = {top: 80,bottom: 60,left: 40,width: 522};
pdf.fromHTML(source, margins.left, margins.top, {
'width': margins.width // max width of content on PDF
, 'elementHandlers': specialElementHandlers
},
function (dispose) {
pdf.save('home.pdf');
console.log( pdfOutput );
var pdfOutput = doc.output();
console.log("file system - ");
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
console.log(fileSystem.name);
console.log(fileSystem.root.name);
console.log(fileSystem.root.fullPath);
fileSystem.root.getFile("test.pdf", {create: true}, function(entry) {
var fileEntry = entry;
console.log(entry);
entry.createWriter(function(writer) {
writer.onwrite = function(evt) {
alert("write success");
};
console.log("writing to file");
writer.write( pdfOutput );
}, function(error) {
console.log(error);
});
}, function(error){
console.log(error);
});
},
function(event){
console.log( evt.target.error.code );
});
},
margins
)
Could someone give me a tip or point me in the right direction on how to incorporate your solution into my coding so I can save html formatting & images?
I just had this same issue.
Here's what I did to solve it.
Replace the line
writer.write( pdfOutput );
with this:
var data = pdfOutput;
var buffer = new ArrayBuffer(data.length);
var array = new Uint8Array(buffer);
for (var i = 0; i < data.length; i++) {
array[i] = data.charCodeAt(i);
}
writer.write(buffer);
Not 100% sure that I understand what's happening, but from what I have been researching, you need to convert the output from jsPDF to an ArrayBuffer before writing to the file.
#AdilWaqar I apologise for the delay in my response, I have been moving house. Below I have included the full javascript I finished on to get pdf printing working. it works perfect in android & IOS but the issue with IOS is that once the pdf has been generated you cannot gain access to it via a file manager.
The localStorage was used for storage before output, it has same id name on the span fields in the output html for that specific section, for example section 3 in the javascript had some signatures and some text boxes to output, the localStorage for one textfield in the output is...
getItem('cwiRiskAccesAsessName')
the html output is...
<tr><td>Assessor Name:</td><td><span id="EXPcwiRiskAccesAsessName"></span></td></tr>
I used jquery to pre-populate the span fields by building the html ready for output and adding a prefix to the id of each item, once done I used this simple line to deal with auto population on keyup. note: ignore 'inpt' in onkeyup, that was for a prefix within another part of the data handling function
onKeyUp="dataHandling(this,1,'inpt');"
var saveData = localStorage.setItem(source.id,source.value);var getData = localStorage.getItem(source.id);$("#EXP"+source.id).text(getData);
Below is the full pdf output javascript
/* STORAGE-OUTPUT */
function storageOutput(){for (var i = 0; i < localStorage.length; i++){
/* do something with localStorage.getItem(localStorage.key(i));*/
$("#storageHolder").append(localStorage.key(i)+'<br/>');}
}
/* SETUP */
function setup(){
window.requestFileSystem(LocalFileSystem.PERSISTENT,0,onRequestFileSystemSuccess,null);
function onRequestFileSystemSuccess(fileSystem){
var entry=fileSystem.root;entry.getDirectory("MAIN-DIRECTORY",{create:true,exclusive:false},onGetDirectorySuccess,onGetDirectoryFail);
}
function onGetDirectorySuccess(dir){}
function onGetDirectoryFail(error){
alert('Directory Setup Fail');}
}/*CLEAR LOCALSTORAGE*/function clearLS(){
localStorage.clear();alert(localStorage.length);
}
function savePDF(id,filename) {
var folderName = 'MAIN-DIRECTORY/'+localStorage.getItem('householderAddress')+', '+localStorage.getItem('householderPostcode');
var saveData = localStorage.setItem('saveLocation',folderName);
var getData = localStorage.getItem('saveLocation');
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onRequestFileSystemSuccess, null);
function onRequestFileSystemSuccess(fileSystem) {
var entry=fileSystem.root;
entry.getDirectory(getData, {create: true, exclusive: false}, onGetDirectorySuccess, onGetDirectoryFail);
}
function onGetDirectorySuccess(dir){}
function onGetDirectoryFail(error){}
if(id==1){
var pdf = new jsPDF('p', 'pt', 'a4'),source = $('#savesec1')[0]
, specialElementHandlers = {
'#bypassme': function(element, renderer){
return true
}
}
} else if (id==2){
var pdf = new jsPDF('p', 'pt', 'a4'),source = $('#savesec2')[0]
, specialElementHandlers = {
'#bypassme': function(element, renderer){
return true
}
}
} else if (id==3){
var pdf = new jsPDF('p', 'pt', 'a4'),source = $('#savesec3')[0]
, specialElementHandlers = {
'#bypassme': function(element, renderer){
return true
}
}
}
margins = {top: 40,bottom: 60,left: 40,width: 522};
pdf.fromHTML(source, margins.left, margins.top, {
'width': margins.width // max width of content on PDF
, 'elementHandlers': specialElementHandlers
},
function(dispose){
/*SECTION 2*/
if(id==2){
pdf.addImage(localStorage.getItem('householderSig1'),'PNG',135,270,150,50);pdf.addImage(localStorage.getItem('assessSig1'),'PNG',135,410,150,50);
}
/*SECTION 3*/
else if(id==3){
pdf.addPage();pdf.setFontSize(15);pdf.setFontType("normal");pdf.text(20,30,'Assessor Name: '+localStorage.getItem('cwiRiskAccesAsessName'));pdf.text(20,45,'Assessor Agency: '+localStorage.getItem('cwiRiskAccesAsessAgency'));pdf.text(20,60, 'Date: '+localStorage.getItem('assessSig3Date'));pdf.text(20,75, 'Assessor Signature: ');pdf.addImage(localStorage.getItem('assessSig3'),'PNG',20,85,250,100);pdf.addPage();pdf.setFontSize(25);pdf.setFontType("normal");pdf.text(20,40,'Plan View:');pdf.addImage(localStorage.getItem('drawingOutput'),'PNG',20,40,500,500);pdf.addPage();pdf.setFontSize(15);pdf.setFontType("normal");pdf.text(20,30,'Front Elevation: '+localStorage.getItem('cwiRiskFrontNotes'));pdf.text(20,430,'Rear Elevation: '+localStorage.getItem('cwiRiskRearNotes'));pdf.addImage(localStorage.getItem('cwiRiskFrontOutput'),'PNG',40,40,500,350);pdf.addImage(localStorage.getItem('cwiRiskRearOutput'),'PNG', 40, 440, 500, 350);pdf.addPage();pdf.setFontSize(15);pdf.setFontType("normal");pdf.text(20,30,'Left Side Elevation: '+localStorage.getItem('cwiRiskLeftNotes'));pdf.text(20,430,'Right Side Elevation: '+localStorage.getItem('cwiRiskRightNotes'));pdf.addImage(localStorage.getItem('cwiRiskLeftOutput'),'PNG',40,40,500,350);pdf.addImage(localStorage.getItem('cwiRiskRightOutput'),'PNG',40,440,500,350);
}
/* GENERIC IMAGE OUTPUT
pdf.addImage(imgData, 'PNG', 40, 400, 400, 160);
pdf.addImage(imgData, 'PNG', 40, 600, 400, 160);
for (var i=0;i<dataSources.length;i++){
pdf.addPage();
alert(dataSources[i].text);
}
pdf.save(filename+'.pdf');*/
var pdfOutput = pdf.output();
//console.log( pdfOutput );
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
fileSystem.root.getFile(getData+'/'+filename+'.pdf', {create: true}, function(entry) {
var fileEntry = entry;
//console.log(entry);
entry.createWriter(function(writer) {
writer.onwrite = function(evt) {
alert("PDF Saved Successfully");
};
console.log("writing to file");
var data = pdfOutput;
var buffer = new ArrayBuffer(data.length);
var array = new Uint8Array(buffer);
for (var i = 0; i < data.length; i++) {
array[i] = data.charCodeAt(i);
}
writer.write(buffer);
}, function(error) {
alert(error);
});
}, function(error){
console.log(error);
});
},
function(event){
console.log( evt.target.error.code );
});
},
margins
)
}
I'm using mmenu library in jquery mobile, when parsing an xml and append the result to:
<nav></nav>
the sub-menus don't work correctly.
here is my js:
<script>
$(document).ready(function(){
$.ajax({
type: "GET",
url: "MainMenuAsXml.xml",
dataType: "xml",
cache: false,
success: function(xml){
var list_elem = $("<ul></ul>");
$(xml).find('module').each(function(){
var module = $(this);
var moduleLabel = module.attr("text");
var directories_list = $("<li class='Selected'></li>").appendTo(list_elem);
module.find("directory").each(function(){
var directory = $(this);
var directoryLabel = directory.attr("text");
var directory_elem = $("<li></li>").append("<span>" + directoryLabel + "</span>").appendTo(directories_list);
var entries_list = $("<ul></ul>").appendTo(directory_elem);
directory.find("entries").each(function(){
var entries = $(this);
var linkName = entries.attr("text");
var myLink = entries.attr("link");
$('<li>' + linkName + '</li>' ).appendTo(entries_list);
});
});
});
$("#menu-left").append(list_elem));
buildMenu();
},
error: function() {
alert("An error occurred while processing XML file.");
}
});
});
</script>
I'm sure that the parsing result is correct but I think there is an error using the function.
and here is the output
I am working on one project and I am using JavaScript code to get a screenshot of the website.
The screenshot is working fine and is rendered nicely on the page.
What I want to do is instead of displaying it on the page, I want to show the 'save as' popup window with the screenshot.
Here is the current code which displays the image on the page:
<script type="text/javascript">
var date = new Date();
var message,
timeoutTimer,
timer;
var proxyUrl = "http://html2canvas.appspot.com";
function addRow(table,field,val){
var tr = $('<tr />').appendTo( $(table));
tr.append($('<td />').css('font-weight','bold').text(field)).append($('<td />').text(val));
}
function throwMessage(msg,duration){
window.clearTimeout(timeoutTimer);
timeoutTimer = window.setTimeout(function(){
message.fadeOut(function(){
message.remove();
});
},duration || 2000);
$(message).remove();
message = $('<div />').html(msg).css({
margin:0,
padding:10,
background: "#000",
opacity:0.7,
position:"fixed",
top:10,
right:10,
fontFamily: 'Tahoma' ,
color:'#fff',
fontSize:12,
borderRadius:12,
width:'auto',
height:'auto',
textAlign:'center',
textDecoration:'none'
}).hide().fadeIn().appendTo('body');
}
$(function(){
$('ul li a').click(function(e){
e.preventDefault();
$('#url').val(this.href);
$('button').click();
})
var iframe,d;
$('input[type="button"]').click(function(){
$(iframe.contentWindow).unbind('load');
$(iframe).contents().find('body').html2canvas({
canvasHeight: d.body.scrollHeight,
canvasWidth: d.body.scrollWidth,
logging:true
});
});
$('button').click(function(){
$(this).prop('disabled',true);
var url = $('#url').val();
$('#content').append($('<img />').attr('src','loading.gif').css('margin-top',40));
var urlParts = document.createElement('a');
urlParts.href = url;
$.ajax({
data: {
xhr2:false,
url:urlParts.href
},
url: proxyUrl,
dataType: "jsonp",
success: function(html){
iframe = document.createElement('iframe');
$(iframe).css({
'visibility':'hidden'
}).width($(window).width()).height($(window).height());
$('#content').append(iframe);
d = iframe.contentWindow.document;
d.open();
$(iframe.contentWindow).load(function(){
timer = date.getTime();
$(iframe).contents().find('body').html2canvas({
canvasHeight: d.body.scrollHeight,
canvasWidth: d.body.scrollWidth,
logging:true,
proxyUrl: proxyUrl,
logger:function(msg){
$('#logger').val(function(e,i){
return i+"\n"+msg;
});
},
ready: function(renderer) {
$('button').prop('disabled',false);
$("#content").empty();
var finishTime = new Date();
var table = $('<table />');
$('#content')
.append('<h2>Screenshot</h2>')
.append(renderer.canvas)
.append('<h3>Details</h3>')
.append(table);
addRow(table,"Creation time",((finishTime.getTime()-timer)/1000) + " seconds");
addRow(table,"Total draws", renderer.numDraws);
addRow(table,"Context stacks", renderer.contextStacks.length);
addRow(table,"Loaded images", renderer.images.length/2);
addRow(table,"Performed z-index reorder", renderer.needReorder);
addRow(table,"Used rangeBounds", renderer.support.rangeBounds);
throwMessage('Screenshot created in '+ ((finishTime.getTime()-timer)/1000) + " seconds<br />Total of "+renderer.numDraws+" draws performed",4000);
}
});
});
$('base').attr('href',urlParts.protocol+"//"+urlParts.hostname+"/");
html = html.replace("<head>","<head><base href='"+urlParts.protocol+"//"+urlParts.hostname+"/' />");
if ($("#disablejs").prop('checked')){
html = html.replace(/\<script/gi,"<!--<script");
html = html.replace(/\<\/script\>/gi,"<\/script>-->");
}
// console.log(html);
d.write(html);
d.close();
}
}); });
});
</script>
For that you can use canvas2image.
I guess you could put in your ready function:
ready: function(renderer) {
....
Canvas2Image.saveAsPNG(renderer.canvas);