Java Applet is undefined - javascript

I have this jzebra applet that I need to do some client side ticket printing.
This is the applets html definition:
<applet id="jzebra" name="jzebra" code="jzebra.PrintApplet.class" archive="../../../../../../web/org.openbravo.howtos/lib/jzebra.jar"
width="10px" height="10px">
The function I call in the form button is this:
function printDocument() {
var applet = document.jzebra;
var frm = document.frmMain;
var url = frm.elements["inpftpOBDir"].value;
var file ="0.txt";
var archivo = url + "/" + file;
if (applet != null) {
var printname = frm.elements["inpPrinterName"].value;
var indice = frm.inpPrinterSelected.selectedIndex;
var printselected = frm.inpPrinterSelected.options[indice].text;
alert(printname);
alert(printselected);
if(printselected == ""){
// printname = "zebra"
//alert('Default : ' + printname);
applet.findPrinter(printname);
monitorFinding();
} else {
//alert('Selected : ' + printselected);
applet.findPrinter(printname);
monitorFinding();
}
alert('File : ' + archivo);
// applet.findPrinter(printname);
applet.appendFile(archivo);
// Send characters/raw commands to printer
applet.print();
alert('The document was sent to the printer.');
}
}
I checked the console and there is a definition of applet, but when it reaches applet.findPrinter(printname), just explodes because applet.findPrinter is not a function.
Has anyone faced this struggle before? I have seen that there is a little gray square in the top left corner of my page. When I hover on it, it displays "undefined".

I finally came up with a very complex solution, having to use jnlp. I will post my code later for references, if anyone else find similar problems.

Related

Javascript redirect using windows.locaton.href OR windows.locaton.replace is not working. Error: window not defined

I have looked at all of the questions around windows.locaton.href and windows.locaton.replace not working, but still can't figure out why this redirect is not working in JavaScript. There are two JS functions I am calling when a button is clicked with submit.
<input type="submit"
onclick="NotifyUserOfNewBudgets('#Field1');redirect2MainLookup('#primaryFilename');"
class="SaveChangeButton" value="Create New Budget">
The two functions are defined in Javascript as:
<script>
function NotifyUserOfNewBudgets(val) {
alert("New Budget will be saved. NewVal=" + val);
var ireturn;
document.getElementById("NewBudgetID").value = val;
document.getElementById("formMode").value = "Update";
}
function redirect2MainLookup(primaryFilename) {
var loc = window.location.pathname;
var host = document.location.host;
var dir = loc.substring(0, loc.lastIndexOf('/'));
//Replace the word Edit with blank so this redirects correctly
var newdir = dir.replace("NewBudget", "");
var newpath = host + newdir + primaryFilename;
alert('newpath location = http://' + newpath);
try {
windows.locaton.href = "http://" + newpath;
//window.location.replace('http://' + newpath);
} catch (err) { alert("Error: " + err);}
}
</script>
The error I get in the try()catch() is windows is not defined and then is stays on the same page. I get the same error using windows.locaton.replace() too. I have lots of pages doing redirects, can't figure out why this one fails.
You have a number of spelling mistakes. window is the object you are looking to reference. location is the property you are looking to access. Right now, you are using windows.locaton. windows is not a thing, nor is locaton. Keep an eye on undefined errors, they can tell you a lot about the state of your code.

Intercept incoming URL with javascript

When a user navigates to my site with a qualified URL (e.g. mysite.com/abc.html) I want to call a javascript function first before showing any pages. I need that because my site is driven by ajax.
I have a function that’s called when the page is first loaded:
<body onload="FirstJSFunction(150);”>
That function will intercept the URL and do what I want, but only if the qualified URL is mysite.com/index.html. Any other valid URL within the site will bypass the javascript function and load the requested page. That’s not what I want.
Here is how FirstJSFunction handles it:
<script>
function FirstJSFunction(type) {
var gurl = GetURL();
length = gurl.length;
console.log("SFR URL " + length);
var pos = gurl.lastIndexOf("/");
console.log ("SFR_LastFwdSlash " + pos);
if (length > pos) {
var sub1 = gurl.substr(pos, length);
console.log ("SFR_Sub1 " + sub1);
sub2 = sub1.substr(1, 5);
console.log ("SFR_Sub2 " + sub2);
if (sub2 == "index") {
ShowAjax(3);
return true; }
if (sub2 != "index") {
ShowAjax(3);
return true; }
}
</script>
<script>
function GetURL() {
var loc_href = location.href;
console.log ("URL " + loc_href);
var length = loc_href.length;
console.log ("Length " + length);
var pos = loc_href.lastIndexOf("/");
console.log ("LastFwdSlash " + pos);
var pos2 = loc_href.indexOf("/");
console.log ("FwdSlash " + pos2);
if (length > pos) {
var substr = loc_href.substr(pos, length);
console.log ("Substring " + substr);
return substr; }
}
</script>
So my question is: when the user navigates to my site with any URL other than mysite.com or mysite.com/index.html – for example mysite.com/abc.html – why doesn’t the code above work to intercept the URL and call the javascript function, as happens if the URL is index.html.
Just to clarify, I only want to intercept the first incoming URL. I am not looking to intercept any URL the user enters into the address bar after they have arrived at my site.
Thanks for any help on this.
I'm not sure about everything you explained, so making some assumptions here.
But if that JS code is only on index.html, then it will never run for any other page. For that you would need to include it in every page.
Only the server is able to "see" all the pages accessed by your users.

Cannot get the number of var using javascript

I have this certain problem where I cannot get the number value of 'currentStock' var data inside an HTML file using JavaScript. I have this on my HTML file in script tag:
By the way, due to the HTML being too large, and also it was not originally my script, but from a friend who was asking for some help on adding some features in it, I can't upload the whole script as it will be going to be too long. The whole HTML script has 14076 characters with 289 lines.
I have only studied java and not javascript with HTML, so I need help with this one.
<script>
window.onload = function() {
var goDown = document.getElementById('uniqueNav');
var goRight = document.querySelector('.clothesNav');
var goUp = document.querySelector('.shrink');
goDown.style.marginTop = "0px";
goRight.style.marginLeft = "5px";
goUp.style.height = "0px";
}
$('document').ready(function(){
var name = "Ombre Printed Shirt";
var price = "P499.00";
var initialStock = 0;
var currentStock = initialStock;
document.querySelector('#clothTitle').innerHTML = "" +name;
document.querySelector('#clothPrice').innerHTML = "Price: " +price;
document.querySelector('#PITitle').innerHTML = "" +name;
document.querySelector('#PIPrice').innerHTML = "Price: " +price;
document.querySelector('#currentStock').innerHTML = "CurrentStocks: " +currentStock;
}); //------------------------Change This Every Document ----------------------------//
</script>
then this in my JavaScript File:
var cStocks = document.getElementById('currentStock').data;
alert(typeof cStocks);
alert("Data in cStocks = " + cStocks);
if (!cStocks) {cStocks = 0; alert("cStocks, not a valid number");}
if ((cStocks <= 0) == true)
{
document.querySelector('.clothButton').style.display='none';
document.querySelector('.clothButtonDisabled').style.display='flex';
}
else
{
document.querySelector('.clothButton').style.display='flex';
document.querySelector('.clothButtonDisabled').style.display='none';
}
upon loading the page, the alert says thaat the data type is undefined. I don't know what's happening with my code. did I miss something?
By the way, I have JQuery on my HTML page. it says JQuery v3.3.1 as a version
It doesn't look to me like #currentStock will have a data attribute, or value attribute (which is for inputs), so of course the js returns undefined. Right now it looks like #currentStock is having the innerHTML set on the document.ready to Current Stocks: 0
You do have an accessible variable, currentStock, which is defined during document.ready. Why aren't you accessing it directly? It will have the numeric value in it already. All you can get from #currentStock is the html you generated on document.ready, and you'd have to parse the number out of it, when it's available in raw form in the js variable currentStock.

parseJSON error (jQuery 1.7.2)

I am attempting to parse a JSON object located on another page on my website. The page is a hosted ecommerce platform, so I don't have server side access or control over certain elements on page.
I have some code that i'm using that is returning a strange error. I've tested this snippet (with a different URL of course) on another site running the same platform and it does it fact work.
website: http://www.falcontechjax.com
$.get('no-risk-diagnostic-2.aspx', function(data) {
var prodImgDetail = $.parseJSON($(data).find("#imginfo").html());
console.log(prodImgDetail);
});
On that page, there is a div container with the id "imginfo, that contains a JSON object.
<div id="imginfo" style="display:none;">{gallery : [{thumbnail : '/images/products/thumb/pipe.jpg', display : '/images/products/display/pipe.jpg', detailed : '/images/products/detail/pipe.jpg', alt : '', title : '' },{thumbnail : '/images/products/thumb/logo_printres1.jpg', display : '/images/products/display/logo_printres1.jpg', detailed : '/images/products/detail/logo_printres1.jpg', alt : 'PC Computer Diagnostic & Repair in Jacksonville FL', title : '' }],active : {thumbnail : '/images/products/thumb/pipe.jpg', display : '/images/products/display/pipe.jpg', detailed : '/images/products/detail/pipe.jpg', alt : '', title : '' }}</div>
The error I get when I run it is:
Uncaught SyntaxError: Unexpected token g jquery-1.7.2.min.js
update
Just to advise everyone, there is a version of this setup which works on another site on the same platform as mine:
Site: www.allvintagegames.com
$.get( "nes-adventures-of-bayou-billy.aspx", function( data ) {
var imgThumb, imgDisplay, imgDetailed, imgAlt, imgTitle;
var mycrap = $.parseJSON($(data).find("#imginfo").html());
//img information
$.each(mycrap.gallery, function(i, object) {
//alert(object);
imgThumb = object.thumbnail;
imgDisplay = object.display;
imgDetailed = object.detailed;
imgAlt = object.alt;
imgTitle = object.title;
});
//product information
var prodinf = $.parseJSON($(data).find("#iteminfo").html());
var infoLowprice = prodinf.lowprice;
var infoId = prodinf.id;
var infoName = prodinf.name;
var infoCaption = prodinf.caption;
var infoPrice = prodinf.price;
var infoSaleprice = prodinf.saleprice;
var infoCode = prodinf.code;
var infoOrderable = prodinf.orderable;
$("body").append("<img src='"+imgThumb+"' />");
$("body").append("<img src='"+imgDisplay+"' />");
$("body").append("<img src='"+imgDetailed+"' />");
$("body").append("<br />");
$("body").append(infoLowprice + "<br/>");
$("body").append(infoId + "<br/>");
$("body").append(infoName + "<br/>");
$("body").append(infoCaption + "<br/>");
$("body").append(infoPrice + "<br/>");
$("body").append(infoSaleprice + "<br/>");
$("body").append(infoCode + "<br/>");
$("body").append(infoOrderable + "<br/>");
});
This last example includes another object (#iteminfo contents) which is reference on the applicable page, just under the #imginfo div.
Any help figuring this out would be most appreciated!
As Felix King says, the JSON text is not properly formatted. You can see it if you try this in your debug console:
JSON.parse('{gallery: "foo"}')
and then this:
JSON.parse('{"gallery": "foo"}')
You'll see that when the key names are unquoted it doesn't work, which is what your JSON string has. One option is to instead use eval() to parse the string. Using eval is a terrible idea generally though, as it puts the code in your page at the mercy of whatever the server returns, which could be malicious code.

Additional function execution after upgrading jquery to 1.6.1

I initially wrote a small ajax-based settings page for an online support system i developed, using jQuery 1.4.2 and it worked fine. However, after upgrading to 1.6.1, additional executions are being called to the functions that were only ever called once previously.
I have three menu options, each with an onclick event to load a specific page into the #settingsph div. Additional code is then called depending on the page in question. (The apache server automatically assumes .php file ext are to be used if none are defined)
function open_page(name) {
$("#settingsph").load("/includes/support/stg/"+name, function(){
if(name == "managecontacts"){
$("#contactselect").load("/includes/support/stg/contactsel");
}else if(name == "changepw"){
$(change_pw(), "changepw_box");
}else if(name == "editcompany"){
$(company_update(), "#company_update");
}
});
}
Once loaded, a select box is presented to users, to select a contact to edit. Onchange, the following function is called.
function open_contact(id) {
$("#contact_info").load("/includes/support/stg/editcontact?id="+id);
if(id != "NewContact") {
$(contact_update(), "#contact_update");
}else{
$(contact_add(), "#contact_add");
}
}
Let's assume the user has decided to edit their contact information (all 3 update pages use roughly the same function, but with the variables changed to reflect the page it took information from).
function contact_update() {
$('input.text-input').css({backgroundColor:"#ffffe0"});
$('input#ldate').live('focus', function(){
$(this).datepick({dateFormat: 'dd/mm/yy'});
});
$("input.text-input").live('focus', function(){
$(this).css({backgroundColor:"#FFFFFF"});
});
$("input.text-input").live('blur', function(){
$(this).css({backgroundColor:"#ffffe0"});
});
$('.error','#contact_info').hide();
$(".buttonupd").live('click', function() {
// validate and process form
// first hide any error messages
$('.error').hide();
var forename = $("input#forename").val();
if (forename == "") {
$("label#forename_error").show();
$("input#forename").focus();
$('input#forename').css({border:"solid #aa0000"});
}else{
$('input#forename').css({border:""});
}
var surname = $("input#surname").val();
if (surname == "") {
$("label#surname_error").show();
$("input#surname").focus();
$('input#surname').css({border:"solid #aa0000"});
}else{
$('input#surname').css({border:""});
}
var phone = $("input#phone").val();
if (phone == "") {
$("label#phone_error").show();
$("input#phone").focus();
$('input#phone').css({border:"solid #aa0000"});
}else{
$('input#phone').css({border:""});
}
var email = $("input#email").val();
if (email == "") {
$("label#email_error").show();
$("input#email").focus();
$('input#email').css({border:"solid #aa0000"});
}else{
$('input#email').css({border:""});
}
if((forename == "") || (surname == "") || (phone == "") || (email == "")){
return false;
}
var contactid = $("input#contactid").val();
var jobtitle = $("input#jobtitle").val();
var site = $("select#site option:selected").val();
var mobile = $("input#mob").val();
var ldate = $("input#ldate").val();
var loginallowed = $("input[name='loginallowed']:checked").val();
var editaddress = $("input[name='editaddress']:checked").val();
var editcontacts = $("input[name='editcontacts']:checked").val();
var editcompany = $("input[name='editcompany']:checked").val();
var lognewissue = $("input[name='lognewissue']:checked").val();
var viewallissues = $("input[name='viewallissues']:checked").val();
var viewchangelog = $("input[name='viewchangelog']:checked").val();
var viewdownloads = $("input[name='viewdownloads']:checked").val();
var newissuenotify = $("input[name='newissuenotify']:checked").val();
var closeissuenotify = $("input[name='closeissuenotify']:checked").val();
var changelognotify = $("input[name='changelognotify']:checked").val();
var viewsitehardware = $("input[name='viewsitehardware']:checked").val();
var viewcompanyhardware = $("input[name='viewcompanyhardware']:checked").val();
var dataString = 'contactid=' + contactid + '&forename=' + forename + '&surname=' + surname + '&jobtitle=' + jobtitle + '&site=' + site + '&email=' + email + '&phone=' + phone + '&mob=' + mobile + '&ldate=' + ldate + '&loginallowed=' + loginallowed + '&editaddress=' + editaddress + '&editcontacts=' + editcontacts + '&editcompany=' + editcompany + '&lognewissue=' + lognewissue + '&viewallissues=' + viewallissues + '&viewsitehardware=' + viewsitehardware + '&viewcompanyhardware=' + viewcompanyhardware + '&viewchangelog=' + viewchangelog + '&viewdownloads=' + viewdownloads + '&newissuenotify=' + newissuenotify + '&closeissuenotify=' + closeissuenotify + '&changelognotify=' + changelognotify;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "/includes/support/stg/contactupd",
data: dataString,
success: function() {
$('#contact_update').html("<div id='contact_upd_msg'></div>");
$('#contact_upd_msg').html("<h2>Contact Successfully Updated</h2>")
.append("<p>Thank you.</p>")
.hide()
.fadeIn(1500, function() {
$('#contactselect').html("")
$("#contactselect").load("/includes/support/stg/contactsel");
});
}
});
return false;
});
}
The first time the function is executed, it is called only once and appears to be fine. However, if the above function is called a second time to perhaps update another contact, two requests are sent, updating the information twice and refreshing the select box with a list of contacts in twice. If the above function is called a third time, three requests are sent and so on until the page is completely refreshed. I reverted back to 1.4.2 and these functions are only ever executed once, regardless of how many times they're called without a page refresh.
The .live() method was introduced to me here on SO when i first wrote the system and worked well at the time since the .buttonupd does not exist in the DOM when the settings.php page is loaded, is this my problem?
As was mentioned in the comment, you shouldn't be attaching events within a function which could be called multiple times. Each time you call live within that function you are attaching a new event handler. That's why if that method gets called 3 times, triggering the event will cause the handler to run 3 times.
Here is a stripped down example:
http://jsfiddle.net/N78MX/
Notice that every time you click, the number of words added increases by one. This is because each click calls live and attaches another handler.
You can fix this by simply moving all of your live calls outside of your function. Since you are using live it is fine to call it prior to the elements in question being created. So the stripped down example becomes this:
http://jsfiddle.net/N78MX/1
and it works no matter how many times you click. (obviously if this were a real page I would combine those two live calls, but this is just for illustration).

Categories