Captcha Refresh Script Only Works Once - javascript

I have a captcha image for form validation and a javascript to refresh the image if it is unreadable for the user. The script works fine in Chrome, but in Firefox it only works the first time and, after that, though the script runs, the image does not refresh. the image src includes:
<?php echo "?rand=" . rand(); ?>
But despite the fact that the php is working just fine, the refresh is still inoperable.
I've checked this, and this, and have tried many of the suggestions - for example adding and removing no cache meta tags, changing the body and head tags to h:body and h:head.
Many of the suggestions (eg the one here) describe code situations different from mine (in my case I am using a php-generated image.
Any help will be very appreciated.
<script type="text/javascript">
function refresh_captcha()
{
var img = document.getElementById('captchaimg');
img.src = 'captcha_code_file.php?rand=<?php echo(rand()); ?>';
document.getElementById ("captchaimg").src = img.src;
//alert("some alert.");
}
The page is here

Try to use this, random not php, but JS.
function refresh_captcha()
{
var img = document.getElementById('captchaimg');
img.src = 'captcha_code_file.php?rand=' + Math.random();
document.getElementById ("captchaimg").src = img.src;
//alert("some alert.");
}

Related

Embedded img doesnt always appear in JavaScript created page

I need to generate an HTML page, with an embedded logo and print it using just JavaScript, no jQuery.
This code works, some of the time. Most times, the image isn't printed, although if you close the print dialog box, the image is then in the generated document.
EDIT
Screen shots - common logo not displayed
Logo displayed
I think what is happening is that the browser hasnt had time to decode the base 64 img before its sent to print.
var player = GetPlayer();
var textEntry1=player.GetVar("Page1");
var textEntry2=player.GetVar("Q2");
var textEntry3=player.GetVar("Page2");
var contents = "<html><head></head><body style='width:650px;padding:20px;'>";
// Logo as base 64 encoded. Its about a 5Kb file. Chopped for clarity
contents+="<img src='data:image/png;base64,iVBOR ... gAAAABJRU5ErkJggg=='>";
contents+="<div style='font-size:26px;font-weight:bold;margin-top:26px;margin-bottom:20px;'>Print Your Answers to PDF or Paper</div>";
contents+="<div style='display:block;border-width:1px';><hr/></div>";
contents+="<div style='font-size:16px;font-weight:bold;'>Question 1</div>";
contents+="<p>"+textEntry1+"</p>";
contents+="<div style='font-size:16px;font-weight:bold;'>"+textEntry2+"</div>";
contents+="<p>"+textEntry3+"</p>";
contents+= "</body></html>";
var myWindow = window.open("","Print","width=810,height=610,scrollbars=1,resizable=1");
myWindow.document.write(contents);
myWindow.print();
I have tried
window.setTimeout(myWindow.print(), 3000);
and
myWindow.setTimeout(myWindow.print(), 3000);
Neither seem to work as the print dialog just appears without the wait.
Also tried myWindow.onload() but that doesn't even open the print dialog.
Thanks
This is a bad practice if you don't need wait 3s: (the bad practice is use setTimeout not the 3s, The time have to be used only when you can not use others events, try to avoid the use)
window.setTimeout(myWindow.print(), 3000);
myWindow.setTimeout(myWindow.print(), 3000);
JS works with some signals, the DOM render is splitted of the rest of execution:
here you can read more about it https://blog.logrocket.com/how-browser-rendering-works-behind-the-scenes-6782b0e8fb10/
Small summary:
Js first execute the full scripts and at the end execute the browse render.
when you use setTimeout js moves these function out of the execution thread, and after the time generate a event for call it.
test some like this:
var myWindow = window.open("","Print","width=810,height=610,scrollbars=1,resizable=1");
myWindow.document.write(contents);
mywindow.document.write('<script type="text/javascript">
window.onload=function() {
mywindow.document.close(); // necessary for IE >= 10
mywindow.focus(); // necessary for IE >= 10*/
window.print();
window.close();
};
</script>');

Dynamically change image src using Jquery not working in IE and firefox

I am implementing a captcha for a email. when click on linkEmail button email modal will open.
there i have to set captcha image generated by a handler (CaptchaGenerator.ashx) on click of linkEmail button click. Here is the code for that.
$(".linkEmail").click(function () {
//Load captcha image
$('.imgCaptcha').attr('src', '/Custom/AppCode/Utilities/CaptchaGenerator.ashx');
$('#emailModal').modal();
});
Above code is working fine in crome but not working in IE and firefox.
Although i have tried followings there is no luck.
HTML:
<p id="captchacontainerp" class="captchacontainer"></p>
-------------------------------------------------------------
$('#captchacontainerp').prepend($("<img id='imCaptcha' class='imgCaptcha' src='/Custom/AppCode/Utilities/CaptchaGenerator.ashx'></img>"));
-------------------------------------------------------------
var img = $('<img id="imCaptcha" class="imgCaptcha">');
img.attr('src', '/Custom/AppCode/Utilities/CaptchaGenerator.ashx');
$('#captchacontainerp').empty();
img.appendTo('#captchacontainerp');
---------------------------------------------------------------
$('#captchacontainerp').empty();
$('#captchacontainerp').append($("<img id='imCaptcha' class='imgCaptcha' src='/Custom/AppCode/Utilities/CaptchaGenerator.ashx'></img>"));
IE caching all GET request, so add a timestamp to your request URL e.g :
$(".linkEmail").click(function () {
//Load captcha image
$('.imgCaptcha').attr('src', '/Custom/AppCode/Utilities/CaptchaGenerator.ashx?'+new Date().getTime());
$('#emailModal').modal();
});
Have you tried setting the src attribute to '' before changing it again?
Also, what are the caching settings you are using (both locally, and on the server)
If you specify any inline style attribute, Height or Width like,
<img src="themes/images/01.png" height="100" width="100" />
<img src="themes/images/01.png" style="height:100px; width=100px;" />
then first remove it and try again.
Even if you externally specify style using style tag,
#imageId{
height : 100px;
width : 100px;
}
then also first remove it and try.
After you remove the style attribute from the images, it will display image.
Height attribute is may work with IE but width attribute not working.
If the above solution doesn't work, then :
Sometime PNG files are not displaying as well. So try to use their JPG image.
I had the same problem when trying to call re captcha button.
After some searching, now function works fine in almost all the famous browsers(chrome,Firefox,IE,Edge,...):
function recaptcha(theUrl) {
$.get(theUrl, function(data, status){});
document.getElementById("captcha-img").src = "";
setTimeout(function(){
document.getElementById("captcha-img").src = "captcha?"+new Date().getTime();
}, 0);
}
'theUrl' is used to render new captcha image and can be ignored in your case. The most important point is generating new URL which forces FF and IE to rerender the image.

Only load the background-image when it has been fully loaded?

Well, the title pretty much describes my question:
How to load the background-image dynamically after it has been fully loaded? Sometimes, I must use backgrounds that are so big that it can take a while for the browser to download it. I'd rather 'load it in the background' and let it fade in when it has been fully loaded.
I think jQuery would be best to be using, but I also want my background to appear if JavaScript has been disabled. If this really isn't possible, so be it, but I think it is?
Best regards,
Aart
........
EDIT:
Thanks a bunch, guys! I've been bugged with this for ages and just couldn't think of a nice and easy way.
I converted Jeffrey's Javascript-solution into a jQuery one, just because jQuery's built-in fade looks so awesome.
I'll just post it here in case anyone else has the same issue:
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
$('#img').css('opacity','0').load(function() {
$(this).animate({
opacity: 1
}, 500);
});
});
</script>
<img src='yourimage.jpg' id='img'/>
If the image is included with an img element:
<img src="bg.jpg" id="img" onload="this.style.opacity='1'">
<script>
document.getElementById("img").style.opacity="0";
</script>
That should load the image normally if JavaScript is disabled, but show it only once it loads assuming it's enabled.
One thing to note (that I overlooked): some browsers will not even attempt to load an image if its display property is none. That's why this method uses the opacity attribute.
You can't do it when JS is disabled. However, what you can do is set the background image in CSS and then use the following script (assuming the element has the ID myelem).
(function() {
var elm = document.getElementById('myelem'),
url = 'background image URL here';
elm.style.backgroundImage = "none";
var tmp = new Image();
tmp.onload = function() {
elm.style.backgroundImage = "url('"+url+"')";
// or insert some other special effect code here.
};
tmp.src = url;
})();
EDIT: Although, make sure your background images are optimal. If they are PNG, try having them Indexed with as small a colour table as possible, or make sure the alpha channel is removed if there is no transparency. If they are JPEG, try adjusting the compression.
Check the example on this page:
http://www.w3schools.com/jsref/event_img_onload.asp
Using "image.onload" will start your code only when the image is ready
Without javascript you can't have events, so you won't be able to know if the image is loaded, at least for the first rendering.
You can also use a css preload (put the image as a background in a hidden div), but that would work better in your first refresh and not while loading.
You can set a variable to the image, and when it loads, set it to the body background:
var my_bg = new Image();
my_bg.src = "url(mybackground.png)";
document.style.backgroundImage = my_bg;
What you are looking for is an image onLoad method. If you set the image with a display:none it wont be visible. To get around the possible lack of javascript, you do the following:
<body style="background-image:url(image.png);">
<img src="image.png" style="display:none" onLoad="changeBackground();" />
</body>
<script>
document.body.style.backgroundImage = "";
function changeBackground(){
document.body.style.backgroundImage = "url(image.png)";
}
</script>
This way, if javascript isnt enabled, the bg will load as normal. If it is, it will display at the end

head.js: weird negative html margin?

Maybe some of you have already some experience with using head.js.
I'm a first-time user and I'm having some problems: as soon as I try to load multiple javascript files my <html> tag get a style="margin-left: -32767px;" applied.
<script type="text/javascript">
var path = "<?php bloginfo('template_directory'); ?>";
head.js( path + "/js/jquery-1.5.min.js", path + "/js/css3-mediaqueries.js",
path + "/js/jquery-cookie.js", path + "/js/scripts.js", function() { });
</script>
Any idea why that happens? When I get rid of that weird style attribute in my html with Firebug all javascript libraries work just fine. However when the page loads the content flickers and as soon as this negative margin gets applied absolutely nothing is visible on my page.
The negative margin is coming from css3-mediaqueries.js
the code is:
var _57 = document.documentElement;
_57.style.marginLeft = "-32767px";
setTimeout(function () {
_57.style.marginTop = "";
}, 20000);
I don't know what purpose this has but you could probably delete this without a problem, if you don't want to do that then I would apply a style on the html tag
style="margin-left:0 !important;"
or with JS:
document.getElementsByTagName("HTML")[0].style.margin = "0"

JavaScript source file not loading in IE8 Popup

I have an issue where the JavaScript source file is loading in popup for IE6, Chrome, Firefox, Safari and Opera. But the same source file is not loading up in IE8.
As a result of this the HTML is not being replaced in the Popup and I am getting an error in IE8 popup saying tinyMCE is not defined
I have referred to Formatting this JavaScript Line and solved issue on all browsers except IE8.
The JavaScript function is as follows:
function openSupportPage() {
var features="width=700,height=400,status=yes,toolbar=no,menubar=no,location=no,scrollbars=yes";
var winId=window.open('','',features);
winId.document.open();
winId.document.write('<html><head><title>' + document.title + '</title><link rel="stylesheet" href="../css/default.css" type="text/css">\n');
var winDoc = winId.document;
var sEl = winDoc.createElement("script");
sEl.src = "../js/tiny_mce/tiny_mce.js";/*TinyMCE source file*/
sEl.type="text/javascript";
winDoc.getElementsByTagName("head")[0].appendChild(sEl);
winId.document.write('<script type="text/javascript">\n');
winId.document.write('function inittextarea() {\n');
winId.document.write('tinyMCE.init({ \n');
winId.document.write('elements : "content",\n');
winId.document.write('theme : "advanced",\n');
winId.document.write('readonly : true,\n');
winId.document.write('mode : "exact",\n');
winId.document.write('theme : "advanced",\n');
winId.document.write('readonly : true,\n');
winId.document.write('setup : function(ed) {\n');
winId.document.write('ed.onInit.add(function() {\n');
winId.document.write('tinyMCE.activeEditor.execCommand("mceToggleVisualAid");\n');
winId.document.write('});\n');
winId.document.write('}\n');
winId.document.write('});}</script>\n');
window.setTimeout(function () {/*using setTimeout to wait for the JS source file to load*/
winId.document.write('</head><body onload="inittextarea()">\n');
winId.document.write(' \n');
var hiddenFrameHTML = document.getElementById("HiddenFrame").innerHTML;
hiddenFrameHTML = hiddenFrameHTML.replace(/&/gi, "&");
hiddenFrameHTML = hiddenFrameHTML.replace(/</gi, "<");
hiddenFrameHTML = hiddenFrameHTML.replace(/>/gi, ">");
winId.document.write(hiddenFrameHTML);
winId.document.write('<textarea id="content" rows="10" style="width:100%">\n');
winId.document.write(document.getElementById(top.document.forms[0].id + ":supportStuff").innerHTML);
winId.document.write('</textArea>\n');
var hiddenFrameHTML2 = document.getElementById("HiddenFrame2").innerHTML;
hiddenFrameHTML2 = hiddenFrameHTML2.replace(/&/gi, "&");
hiddenFrameHTML2 = hiddenFrameHTML2.replace(/</gi, "<");
hiddenFrameHTML2 = hiddenFrameHTML2.replace(/>/gi, ">");
winId.document.write(hiddenFrameHTML2);
winId.document.write('</body></html>\n');
winId.document.close();
}, 300);
}
Additional Information:
Screen shot of the page
Rendered HTML
Original JSPF
please help me with this one.
Why are you using actual DOM functions to add the <script> tag that includes tinymce.js but everything else is using document.write?
I think that's also where your problem lies, as <head> is within <html>, which is not yet closed where you want to append said <script> tag.
Otherwise, you could use the existing <script> tag in the popup to add the code that includes the required external javascript file. If that makes any sense.
So, basically I'm saying, try it the same way as everything else is in your script, using document.write.
(quick addition) I'm not saying this is the 'best' way to do this, I would recommend creating an actual page instead of dynamically creating one in the popup. But in this scenario, I think what I wrote earlier might solve the problem you are having.

Categories