Print content of popup dialong by javascript in backbone project - javascript

I have a button in and it is used for calling a dialog. Dialog's content is a pdf got from jasper report.
Here is the backbone view of dialog :
var framSrc = getRSUR; //getting pdf from jasper reporting server
var ReportView = Backbone.View.extend({
tagName : "div",
id : "report",
initialize: function() {
},
events : {
'click #print' : 'printDialog'
},
'printDialog' : function(){
printReport();
},
render: function(){
this.$el.html('<div><a id="print"><img src="printer.png" width="30px"><span style="position:relative;bottom:10px; left:10px;">Print Report</span></a></div><iframe id="agingFrame" src="'+framSrc+'"></iframe>');
return this;
}
});
printReport() :
function printReport(){
try{
var oIframe = document.getElementById('agingFrame');
var oContent = document.getElementById('agingFrame').innerHTML;
var oDoc = (oIframe.contentWindow || oIframe.contentDocument);
if (oDoc.document) oDoc = oDoc.document;
oDoc.write("<html><head><title>title</title>");
oDoc.write("</head><body onload='this.focus(); this.print();'>");
oDoc.write(oContent + "</body></html>");
oDoc.close();
}
catch(e){
self.print();
}
}
But what I've got from printing is the full page of the web page, not the pdf content in iframe.

Related

How to change qr code filename while downloading the file using html.twig and javascript

I have a qr-code button. On click, qr-code is generated and dialog to save the image format pops-up. In which the filename always comes as "qrcode.png". I have to dynamically change the filename to the name of the files from where the qr-code is generated.
Please, help. I am new to this technology.
HTML TWIG
<th data-field="QR-BTN" data-width="60px" data-orderable="false">{{ 'QR'|trans }}</th>
JAVASCRIPT
var QREXPORT = (function() {
var qrCodeExport = function (e){
e.preventDefault();
//goqr.me api url
const QRCODE_API_URL = "https://api.qrserver.com/v1/create-qr-code/?"; //Library Used
var $form = $('#modal-qr-export-offering'),
qrFormat = $("input[name='qrCodeType']:checked").val(),
jsFormData = $form.data('bs.modal'),
accessCode = jsFormData.options.accesscode;
var params = {
data: "SESSION-" + accessCode,
size: "250x250",
margin: 0,
download: 1,
format: qrFormat,
};
window.location.href = QRCODE_API_URL + $.param(params);
};
return {
init: function() {
$(document).ready(function(){
$('#radioSvg').prop('checked', true);
$('#modal-qr-export-offering').on('hidden.bs.modal', function() {
location.reload();
});
});
$(document).on('click', '.js-btn-submit-form', qrCodeExport);
}
};
})();
QREXPORT.init();
Try using the a tag with download attribute...?
const linkEl = document.createElement('a')
linkEl.href = QRCODE_API_URL + $.param(params);
linkEl.download = 'download-name-here.png'
document.body.appendChild(linkEl)
linkEl.click()
// Maybe remove the link after it worked...?
linkEl.remove()

Backbone.js's Ajax call different behavior in Chrome and Firefox

I am facing a weird issue in Firefox. We are loading a page and while calling Routers.initializeRouters(); an ajax request is sent to fetch the data and loadFormSuccessHandler function populate response into the views.
In case of Chrome, Ajax request waits for views to be initialized then data get populated into the view with ajax response.
In case of Firefox, Ajax request fetch the data and start populating the view and it fails because some of the views still not initialized.
How can I notify ajax request to wait for views to be initialized before populating data.
Any pointers will be helpful.
Main.js
var Main = {
treeView : null,
formView : null,
mainTabBarView : null,
currentFieldView : null,
designModeViewPointer : null,
carousel : null,
advancedControlsView : null,
renderUI : function() {
Templates.loadTemplateList();
Utility.initializeFieldHandlerMap();
Views.showBody();
Routers.initializeRouters();
var form = new Models.Form();
this.formView = Views.showForm('formDetailsDiv', form);
this.treeView = new Views.TreeView({
el : $('#controlsTreeDiv'),
model : null
});
this.treeView.getTree().attachEvent("onDblClick",
ControlBizLogic.formTreeNodeClickHandler);
Main.mainTabBarView = new Views.TabBarView({
el : $('#csdOperationsContainer'),
model : null
});
Views.showControlTab('control');
this.carousel = $('#controlTypesSlider');
this.carousel.tinycarousel();
Main.advancedControlsView = new Views.AdvancedPropertiesTabView({
el : $('#advancedControlProperties'),
model : null
});
// init design mode
Main.designModeViewPointer = new Views.DesignMode({
el : $("#design")
});
Routers.designModeOnBeforeDragEvent();
Routers.designModeOnDragEvent();
}
}
Main.renderUI();
Method with ajax call response
loadForm : function(_id, edit) {
$("#formWaitingImage").show();
if (Main.formView == null) {
Main.formView = Views.showForm('formTab',
new Models.Form({
"id" : _id
}));
}
Main.formView.getFormModel().set({
id : _id
});
GlobalMemory.editForm = (edit == "true");
Main.formView.getFormModel().fetch({
url : 'csdApi/form/' + _id + "/" + edit,
success : this.loadFormSuccessHandler
});
// save as
},
loadFormSuccessHandler : function(model, response) {
var formId = model.get('id');
if (formId != undefined && formId != null) {
GlobalMemory.editForm = true;
}
Routers.formEventsRouterPointer.updateUI(model);
Routers.formEventsRouterPointer.loadFormulae(Main.formView
.getFormModel(), "", "");
AdvancedControlPropertiesBizLogic
.loadSkipRules(Main.formView.getFormModel());
Main.formView.getFormModel().set({
skipRules : model.get('skipRules'),
id : model.get('id')
});
Main.advancedControlsView.setTableCss('formulaTable');
// Main.mainTabBarView.loadFormSummary();
Main.mainTabBarView.getFormSummaryView().displayFormInfo(
model.getFormInformation());
$("#formWaitingImage").hide();
// save form
if (!GlobalMemory.editForm) {
$('#saveForm').prop("value", " Save As ")
}
},
This issue was related to specific firefox version and it was fixed in the next firefox release.

Multiple messages from main script to contentscript

I am using the code below to get file-size of a remote file inside a Firefox Addon being developed using Mozilla Addon SDK.
main.js
// Import the page-mod API
var pageMod = require("sdk/page-mod");
// Import the self API
var self = require("sdk/self");
// Create a page mod
pageMod.PageMod({
include : "*.example.com",
contentScriptFile : [self.data.url("content.js"), self.data.url("jquery.min.js"), self.data.url("contentloaded.js")],
contentScriptWhen : "ready",
attachTo: ["top", "existing"],
onAttach : startListening,
contentScriptOptions : {
iconWait : self.data.url("wait.gif"),
iconFinished : self.data.url("done.png"),
}
});
function startListening(worker) {
worker.port.on("GetSize", function (data) {
// Handle the message
let getReq = require("sdk/request").Request({
url : data[0],
onComplete : function (response) {
reply = [response.headers["Content-Length"], data[1]];
//console.log("Send linkID : " + reply[1]);
worker.port.emit('receiveSize', reply);
}
}).head();
});
}
This works perfectly but the the DisplaySize function gets called multiple times for the same request.
content.js
function checkURL(url, linkID) {
data = [url, linkID];
self.port.emit("GetSize", data);
self.port.on("receiveSize", DisplaySize);
console.log("Inside checkURL For linkID : " + linkID); //<--This displays only once for each request
}
function DisplaySize(data) {
console.log("Inside DisplaySize For linkID : " + data[1]); //<--But this thrice
}
What am I missing here?
Each time you call port.on a new message listener is added. Only call it once.
function checkURL(url, linkID) {
data = [url, linkID];
self.port.emit("GetSize", data);
console.log("Inside checkURL For linkID : " + linkID);
}
function DisplaySize(data) {
console.log("Inside DisplaySize For linkID : " + data[1]);
}
self.port.on("receiveSize", DisplaySize);

Backbone search (always not found)

my searchform with backbone works.. except it always says that the item is not found so I think I always send an empty array so yes, then it's logic it won't find anything.
My searchresult view:
var ArtikelSearchResultsView = Backbone.View.extend({
el: '#searchResults',
render: function ( query_encoded ) {
var query = decodeURIComponent(query_encoded.replace(/\+/g, "%20"));
var result_artikels = _.filter(this.model.models, function (artikel_model) {
var artikel = artikel_model.attributes;
for (var key in artikel) {
if ( artikel[key].toLowerCase().indexOf( query.toLowerCase() ) >= 0 )
{
return true;
}
}
return false;
});
// Show results
var template = $("#search-results").html();
var result_html = _.template( template, { artikels: result_artikels, query: query } );
this.$el.html( result_html );
}
});
My router sends this:
searchResults: function(query){
artikelSearchView.render(query);
var artikelSearchResultsView = new ArtikelSearchResultsView({ model: Artikel });
artikelSearchResultsView.render(query);
}
Artikel is in this case:
var Artikel = Backbone.Model.extend({
urlRoot: 'api/items.json',
defaults: {
titel: 'Titel niet opgegeven',
url_titel: 'unieke sleutel urltitel',
img_path: 'geen image toegevoegd',
commentaar: 'Commentaar niet opgegeven',
categorie: 'Categorie niet opgegeven',
waardering: 0,
artikel: 'Artikel niet opgegeven'
},
initialize: function(){
if(!this.get('description')){
var lazy = 'This user was too lazy too add a description';
this.set('description', lazy);
}
}
});
Full code: http://pastebin.com/Y9zi6aGH (Awere that I use Artikel and Artikels in different ways, I know it's bad practice but that's the way I go for now) So my question is: Can someone fix me this so I get searchresult? If I press "a" that should give allmost all my objects but it gives me nothing in results.
I have made some changes to your code in order to work :
1- In your view ArtikelSearchResultsView, I have bound it's model (collection) reset event to it's render method, thus once it's model is reset from the server it call it's render method :
var ArtikelSearchResultsView = Backbone.View.extend({
el: '#searchResults',
initialize: function(){
this.model.bind('reset', this.render, this);
} ...
2- change
var artikels = new Artikels();
var artikel = new Artikels();
to
var artikels = new Artikels();
var artikel = new Artikel();
3- And finally change your router :
searchResults: function(query){
var artikelSearchResultsView = new ArtikelSearchResultsView({ model: artikels });
artikels.fetch();
}
I have also removed the filtering from ArtikelSearchResultsView render method in order to test it, now the 'this.model.models' is populated with the data you receive from the server.

Catching form submissions in Backbone

I have a URL route that has a parameter whose value is not known ahead of time when the page is loaded. For example:
/read/book/page/:page
But when the user is selection screen they get to type in which page number they want to start on then click submit. Is it possible to catch this form submission and place it in the URL? Normally there is a question mark (?) right because its a GET request. But Backbone how can backbone catch that?
Demo:
http://jsfiddle.net/vpetrychuk/PT2tU/
JS:
var Model = Backbone.Model.extend({
url : function () {
return 'http://fiddle.jshell.net/echo/json?page=' + this.get('page');
},
// remove it
parse : function (response) {
response || (response = {});
response.justToTriggerChangeEvent = Math.random();
return response;
},
getPageContent : function () {
return 'Here should be page a content for page #' + this.get('page');
}
});
var View = Backbone.View.extend({
el : '[data-page]',
events : {
'submit' : 'submit'
},
initialize : function () {
this.listenTo(this.model, 'change', this.showPage);
},
showPage : function () {
this.$('[data-page-content]').html(this.model.getPageContent());
},
submit : function (e) {
e.preventDefault();
var page = this.$('[data-page-num]').val();
if (page) {
app.navigate('read/book/page/' + page, true);
}
}
});
var Router = Backbone.Router.extend({
routes : {
'read/book/page/:page' : 'page'
},
initialize : function (options) {
this.bookModel = options.bookModel;
},
page : function (page) {
this.bookModel.set('page', page);
this.bookModel.fetch();
}
});
var model = new Model();
var view = new View({model:model});
var app = new Router({bookModel:model});
Backbone.history.start();
HTML:
<div data-page>
<form>
<label><input type="text" data-page-num /></label>
<button type="submit">Submit</button>
</form>
<div data-page-content></div>
</div>

Categories

Resources