bad request when trying to print a page using javascript - javascript

I am trying to print a page using javascript, and i am getting a "Bad Request" when a new window popsup if i clicked the 'print' button.
Here is my javascript code that opens a window by capturing the current location and assigning the media css to print.
function printerFriendlyNew() {
genPopUp = window.open("","printer","toolbar=no,location=no,scrollbars=yes,directories=no,status=yes,menubar=yes,resizable=yes,width=760,height=600");
genPopUp.location.href = document.location.href + "&css=print";
if (genPopUp.opener == null) genPopUp.opener = window;
genPopUp.opener.name = "opener";
}
Any idea why i get the 'bad request' error ?

Got this resolved... crazy me, am just blindly appending "&css=print" since I have URLs which have querystring, and it works fine for those, and bugs out for those which don't. I added this to my existing javascript and this resolved the issue.
var contain = document.location.href;
if (contain.indexOf('?') == -1)
genPopUp.location.href = contain + "?css=print";
else
genPopUp.location.href = contain + "&css=print";

Related

HTML + JS: Clear File Input on button click

I want to tell my backend, I deleted the assigned file it already loaded:
<input id="pic" name="pic" type="file" onclick="this.value=null;" onchange="uploadFile(this);">
<button id="pic-delete" type="button" onclick="removeFile(this);"><i someicon></i></button>
where the onclick function looks like:
removeFile = function() {
var ipt = document.getElementById("pic");
ipt.value = null; // <--- problem here
console.log("worked...")
}
my problem now is: I can differentiate the request in the browser Network tab whether I do nothing or hit the delete button. Both times the input field does not show up.
I wanted to add ipt.value="DELETE" so I can catch that in the backend, but this leads to an error:
Uncaught DOMException: An attempt was made to use an object that is not, or is no longer, usable
From what I can tell the error always occurs if I put anything else but ipt.value = null or ipt.value = "" in this line.
A fiddle with the full code to show the error: https://jsfiddle.net/rvc8sbjy/3/
There are a few errors. The way you were trying to extract the ID is wrong. A much easier approach is to just use .replace
var inputFieldID = v.id.replace("-delete", "");
Second - you can't set the value to an non-empty string. To reset it just set it to an empty one:
ipt.value = "";
Working example:
https://jsfiddle.net/5yqohjzv/

Creating a chrome extension to grab all page HTML

I'm attempting to create a chrome extension to grab all website data. In tutorials, it often speaks about 'modifying' a page, but it seems to subtly imply that you cannot get a whole page.
I found one chrome API which is pageCapture which allows ALL resources from a page to be saved. Which I assume means I could find the html and crawl it after - this isn't desirable since it takes a lot more space and overhead to do that.
I'd prefer if there was some way to crawl the active tab. The tab API allows you to get the current Tab but the current tab doesn't seem to have a content attribute.
There must be a better way to do that. Anyone know how to get the current page HTML?
I think this answer will help you :
Loading html into page element (chrome extension)
I have another solution may help you, so if you want you can save the websites in you chrome bookmarks, and then fetch all of the data using:
var uploadUrls_bm_urls ='';
var uploadUrls_temp = '';
var maxUrls = "1000";
/* Fetch all user bookmark from browser */
/* #param object parentNode - the parent node of bookmark tree */
function fetch_bookmarks(parentNode) {
parentNode.forEach(function(bookmark) {
if(! (bookmark.url === undefined || bookmark.url === null)) {
uploadUrls_bm_urls = uploadUrls_bm_urls + '"' + bookmark.url + '",';
if(uploadUrls_bm_urls.length <= maxUrls )
uploadUrls_temp = uploadUrls_bm_urls;
}
if (bookmark.children) {
fetch_bookmarks(bookmark.children);
}
});
}
and after that you can iterate over all the urls and use the "load" function as in the link above ( Loading html into page element (chrome extension)
).
Let me know if this helped you or not.
Thanks

Retrieve URL Parameters Sent Through JQuery .load()

I am not sure if what I'm trying to do is possible or if I'm going about this the right way. In some circumstances I want them to have a GET parameter as part of the URL. I want the receiving page to be able to differentiate whether the sending load has a parameter or not and adjust accordingly.
Here is what I have that is sending the load:
$(document).ready(function () {
$("a").click(function () {
$("div.pageContent").html('');
$("div.pageContent").load($(this).attr('href'));
return false;
});
});
In this case, the load could have "example.php" or "example.php?key=value". In looking around (primarily on this site), I've found things that seem to be close, but don't quite get there. In the page that is getting loaded (example.php), I have the following:
function $_GET(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if (results == null)
return "";
else
return results[1];
}
$(document).ready(function () {
var URL = "example2.php";
if ($_GET('key'))
{
URL = "example2.php?key=" + $_GET('key');
URL = URL.split(' ').join('%20');
}
$("div.output").load(URL);
});
If the sending source includes a query string, I want to add that to the URL and load it in a div that is unique to this page, otherwise I want to just load it as is without the query string. The big issue I'm running into (I believe) is since this is coming from an AJAX call, the "window.location.href" is not what was sent from the JQuery but rather the URL of the root page which never changes. Is there a way to be able to know what the full URL is that was sent from the load() in the first page by the second one?
Thank you in advance for your help.
I realized that the GET parameters were getting passed as I could access them through php without issue. I didn't know that I could insert php code into a javascript block but once I tried it, all worked out. My new code looks like this:
$(document).ready(function () {
var URL = "example2.php";
var myValue = "<?php echo $_GET['key']; ?>";
if (myValue !== "")
{
URL = "example2.php?key=" + myValue;
URL = URL.split(' ').join('%20');
}
$("div.output").load(URL);
});
I was able to get rid of the GET function out of javascript entirely. I probably made this much more difficult from the start but hopefully it can help someone else in the future.

Changing browser windows with window.location in javascript

I have a web site that is in two languages, English and French. now i do not know java-script, I created a code for showing different pictures using javascript depending on which language u want to use.
So if you are on the www.my-site.com/en/ you will see En_pic_ pictures same goes for the opposite.
/*These are the Popup images for the English and French portal */
var url1 = 'http://www.my-site.com/fr/';
var url2 = 'http://www.my-site.com/en/';
MagnifImage.setup(
if (window.location = 'url2'){
"En_pic_1", "/images/1.png","",
"En_pic_2", "/img/content/tracking_instructions/2.png", "",
"En_pic_3", "/img/content/tracking_instructions/3.png", "",
"En_pic_4", "/img/content/tracking_instructions/4.png", "",
}else{
"Fr_pic_1", "/img/content/tracking_instructions/1_fr.png", "",
"Fr_pic_2", "/images/mon-compte.png","",
"Fr_pic_3", "/img/content/tracking_instructions/3_fr.png","",
"Fr_pic_4", "/img/content/tracking_instructions/4_fr.png",""
}
);
Everything works but if I am on the other language page I get an alert box saying there is no Fr_pic_1 or En_pic_1.(depending on the current page I am in) The code I found to accomplish this as follows:
if( !(objRef.trigElem=document.getElementById( idParts[0] )) )
alert("There is no element with the ID:'"+idParts[0]+"'\n\nCase must match exactly\n\nElements must be located ABOVE the script initialisation.");
else
{
if(objRef.trigElem.parentNode && objRef.trigElem.parentNode.tagName=='A')
objRef.trigElem=objRef.trigElem.parentNode;
objRef.classId=idParts[1] || "MagnifImage" ;
objRef.imgObj=new Image();
objRef.imgObj.imgIndex=i;
objRef.imgObj.hasLoaded=0;
its a code I found at http://scripterlative.com?magnifimage
Please help....
You need to fix multiple things:
You must use == or === for comparison. A single = is assignment, not comparison.
You must compare to the variable name url2, not a quoted string 'url2'.
You must fix the way you pass the alternate parameters to your function MagnifImage.setup().
I switched to using window.location.href because window.location is an object and I find it better to use the actual attribute of that object you want rather than rely on an implicit conversion.
Change your code to this:
/*These are the Popup images for the English and French portal */
var url1 = 'http://www.my-site.com/fr/';
var url2 = 'http://www.my-site.com/en/';
if (window.location.href == url2) {
MagnifImage.setup("En_pic_1", "/images/1.png","",
"En_pic_2", "/img/content/tracking_instructions/2.png", "",
"En_pic_3", "/img/content/tracking_instructions/3.png", "",
"En_pic_4", "/img/content/tracking_instructions/4.png", "");
} else {
MagnifImage.setup("Fr_pic_1", "/img/content/tracking_instructions/1_fr.png", "",
"Fr_pic_2", "/images/mon-compte.png","",
"Fr_pic_3", "/img/content/tracking_instructions/3_fr.png","",
"Fr_pic_4", "/img/content/tracking_instructions/4_fr.png","");
}
Your code was likely causing many errors and thus not executing at all. You should learn how to look for javascript errors. Every browser has an error console that will show you javascript parsing or executing errors. Many browsers now have a built-in debugger than has a console in it that will also show you such information and allow you to see the exact source line causing the error. I use Chrome which has a built-in debugger which will do this. Firefox has a free add-on called Firebug that will do this.

Export data using JSON

I need to export data in excel file.I am using JSON post for the same.Its working fine in every browser except IE. Have a look at my javascript code as follow:-
function ExportQueryData() {
var Qry = $("#txtQueryInput").val();
if ($.trim(Qry) == "") {
$("#txtQueryInput").addClass("error");
return false;
}
else
$("#txtQueryInput").removeClass("error");
var url = "/Reports/ExportQueryData";
var frmserialize = $("#frmQuery").serialize();
$.post(url, frmserialize, function(data) {
data = eval("(" + data + ")");
if (data.Success) {
url = "/Reports/Export";
var win = window.open(url, "DownloadWin", "resizable=0,status=0,toolbar=0,width=600px,height=300px");
win.focus();
win.moveTo(100, 100);
return false;
}
else {
Notify("DB Query", data.Message);
}
});
}
As per above code, i am calling /Reports/Export action using window.open. This pop up getting open for every browser except IE. In IE pop up get close simultaneously in 1 or 2 seconds.
I need to use JSON post because it validate input and then returns success status.I can validate my data only at server side.
Let me know if any information is missing here.
Your suggestion will be valuable for me.
Thanks.
I think you've got a pop up blocker situation... Frankly, I don't think opening up stuff in a pop up is a good idea anymore. Browsers seem to hate it.
You could instead show the user a link to the file, asking him to click to download.

Categories