Struggling with onUnload - javascript

I am trying to write some javascript which asks a user, when they leave the page, if they want to fill out a survey (however annoying this may be!). I thought my solution was found by an answer on this site. This is the code I currently have that does not seem to be working:
<script language="javascript">
function comfirmsurv() {
var ConfirmStatus = confirm("We would love to receive your feedback on your experience of this page. Would you like to complete our short survey?");
if (ConfirmStatus == true) {
window.open("#");
}
else
{window.close();}
}
}
window.onUnload=confirmsurv()
</script>
<body>
Test
</body>
Any help is greatly appreciated.

You are assigning the result of calling the function, not the function itself:
window.onunload = confirmsurv; // Note no ()
A few other issues:
Javascript is case sensitive, the property you are after is "onunload", not "onUnload".
The name of the function is "comfirmsurv" but you are assigning "confirmsurv"
window.close() : you can only close windows you open, not others.
There is an extra }.
The language attribute for script elements has been deprecated for over a decade, the type attribute is required, use type="text/javascript"

The unload property is incorrectly stated as onUnload instead of onunload. Also, the code have too many errors here and there.
The browser's console log provides a log that you can use to find the cause of error.
Here's the fixed script.
<SCRIPT>
function confirmsurv() {
var ConfirmStatus = confirm("We would love to receive your feedback on your experience of this page. Would you like to complete our short survey?");
if (ConfirmStatus == true) {
window.open("#");
} else {
window.close();
}
}
window.onunload=confirmsurv;
</SCRIPT>

Related

What could be causing: "Uncaught TypeError: this.captcha_ip.form.submit is not a function" in this (downloaded) javascript?

I'm a total noob to javascript and also this is my first time doing anything but reading this website so maybe I have gone about this all wrong. I've been using PHP+HTML as a hobby for almost 20 years for basic, static websites, but for an M.Arch university project I decided to build a website for a zine, which includes a contact form where I'd like people to be able to submit articles and attachments.
I downloaded an example form and reskinned it to fit the site, but for some reason, the javascript - which I haven't altered in any way - doesn't seem to work. The source website ( https://html.form.guide/contact-form/contact-form-attachment/ ) doesn't seem to have a contact form for me to ask them what's what, and a bit of googling and looking through other stack overflow questions isn't helping, possibly because I don't know enough about javascript to even have the right keywords.
When I inspect the form in my browser, clicking the submit button brings up this error:
Uncaught TypeError: this.captcha_ip.form.submit is not a function
at FG_CaptchaValidator.OnSuccess (fg_captcha_validator.js:42)
at _OnSuccess (fg_captcha_validator.js:120)
at XMLHttpRequest._StateHandler (fg_captcha_validator.js:143)
Here's the function in the downloaded javascript (I really have absolutely no clue where to even begin to bugtest something like this) that the line is part of:
function FG_CaptchaValidator(captcha_ip,captcha_img)
{
this.captcha_ip = captcha_ip;
this.captcha_img = captcha_img;
this.validatedCode=''
this.validate = function()
{
if(this.validatedCode.length==0 ||
this.validatedCode != this.captcha_ip.value)
{
this.ValidateOnline();
return false;
}
else
{
return true;
}
}
this.OnSuccess = function()
{
var msg = this.GetResponseText();
if(msg == 'success')
{
this.validatedCode = this.captcha_ip.value;
if(this.captcha_ip.form.onsubmit())
{
this.captcha_ip.form.submit();
}
}
else
{
sfm_show_error_msg(msg,this.captcha_ip);
document.error_disp_handler.FinalShowMsg();
}
}
this.ValidateOnline = function()
{
var url = captcha_img.src;
var postStr = this.captcha_ip.name + "=" +
encodeURIComponent( this.captcha_ip.value )+'&fg_validate_captcha=y';
this.Init('POST', url);
this.Send(postStr);
}
}
I hope there's something obvious that's just slightly off in this code, because I really don't know where to start with javascript. I know it's a bit like PHP, lots of similar functionality, just at different ends... but the actual syntax..?
If it's not this code, then perhaps I've messed something up in my reskin of the contact form itself, or the way the scripts are included, or, I don't know.. Any guidance would be appreciated!
EDIT TO BRING STUFF IN FROM COMMENTS/ELABORATE: Within my <head> section for every page I bring in metajava.php: <?php require("metajava.php"); ?> within that file I have the scripts included (amongst others): <script type="text/javascript" src="scripts/gen_validatorv31.js"></script> <script type="text/javascript" src="scripts/fg_captcha_validator.js"></script>
I think these two scripts must be getting included correctly, or the browser's inspection console (I use Brave) wouldn't be pointing me to the proper line of the script in the error, and the scripts wouldn't show up in the sources tab(?)
I don't get any 404 errors; the form simply does not submit or appear to do anything unless I'm inspecting the page and see the console error. If I click submit once (with the inspect console open) I get the error I quoted at the beginning, and if I slam it repeatedly like the migrainous bean I am lately, I get a 500 error.
I've also done a little test of the PHP includes by way of adding
echo "filename-for-each-required-include.php included"; to each php include with the title of the file, and they all come in at the top correctly, though it breaks the captcha so I've removed it again now that I know they're working.
I still wonder if it's a javascript syntax thing that I'm not picking up bc I don't know anything really about javascript. I have modified a few simple scripts before but it was VERY trial and error and this is such a complicated looking expression I don't know where to start - is it even meant to be a function?
PS: Thanks for literally YEARS of solving my problems without my even needing to sign up and ask <3

window.onbeforeunload in Chrome: what is the most recent fix?

Obviously, window.onbeforeunload has encountered its fair share of problems with Chrome as I've seen from all the problems I've encountered. What's the most recent work around?
The only thing I've got even close to working is this:
window.onbeforeunload = function () { return "alert" };
However, if I substitute return "alert" with something like alert("blah"), I get nothing from Chrome.
I saw in this question that Google purposefully blocks this. Good for them... but what if I want to make an AJAX call when someone closes the window? In my case, I want to know when someone has left the chatroom on my website, signalled by the window closing.
I want to know if there's a way to either
(a): fix the window.onbeforeunload call so that I can put AJAX in there
or
(b): get some other way of determining that a window has closed in Chrome
Answer:
$(window).on('beforeunload', function() {
var x =logout();
return x;
});
function logout(){
jQuery.ajax({
});
return 1+3;
}
A little mix and match, but it worked for me. The 1+3 makes sure that the logout function is being called (you'll see 4 if it's successful on the popup when you try to leave).
As of Chrome 98.0.4758.109 and Edge 100.0.1185.29, Chromium has not met the standard. There is a bug report filed, but the review is abandoned.
Test with StackBlitz!
Chrome requires returnValue to be a non-null value whether set as the return value from the handler or by reference on the event object.
The standard states that prompting can be controlled by canceling the event or setting the return value to a non-null value.
The standard states that authors should use Event.preventDefault() instead of returnValue.
The standard states that the message shown to the user is not customizable.
window.addEventListener('beforeunload', function (e) {
// Cancel the event as stated by the standard.
e.preventDefault();
// Chrome requires returnValue to be set.
e.returnValue = '';
});
window.location = 'about:blank';
Here's a more straightforward approach.
$(window).on('beforeunload', function() {
return "You should keep this page open.";
});
The returned message can be anything you want, including the empty string if you have nothing to add to the message that Chrome already shows. The result looks like this:
According to MDN,
The function should assign a string value to the returnValue property
of the Event object and return the same string.
This is the following
window.addEventListener( 'beforeunload', function(ev) {
return ev.returnValue = 'My reason';
})
This solved my problem why it wasn't working in my app:
Note that the user must interact with the page somehow (clicking somewhere) before closing its window, otherwise beforeunload is ignored in order not prevent abuse.

Chrome fails to redirect URL when told to via javascript

function test(){
alert("This message should show");
window.location.href = "http://www.google.com";
alert("This message should NOT show");
}
<href="#" onClick=test()>Click Me</a>
Step through using Firefox(v8): The second message does NOT show.
Step through using chrome (v15, v16): BOTH alerts show.
Chrome blows past the redirect and continues through the rest of the call stack (in this case, it finishes the onClick) before redirecting.
No JavaScript Errors.
All extensions disabled.
I'm using a blank html file with no external files loaded.
Does anyone know of a way to get chrome to execute the window.location change immediately?
Pretty sure the specs give you no guarantees for this one, so I'm not too surprised. The obvious solution would be to throw an exception right after. Assuming you don't have catch blocks littered around your code, that ought to work:
throw "Aborting, redirecting you.";
(Yes, it's ugly. Sorry!)
Edit: fiddles: without throw, with throw
You could add a return
function test(){
alert("This message should show");
window.location.href = "http://www.google.com";
return;
alert("This message should NOT show");
}
There is a better way to do this.
function test(){
alert("This message should show");
return true;
alert("This message should NOT show");
}
<href="http://www.google.com" onClick="return test()">Click Me</a>
Optionally, you can use a confirm to control whether or not this action can be performed on click. Blame Google for trying to mess with functional standards, no other browser forces you to do this.
I was just trying the same thing: redirect using JS. In the PHP script I have, if a certain condition is true, I just end the script with a die function, echoing a script tag with the redirect code:
die("<script type='text/javascript' charset='utf-8'>\n".
"window.location.href='http://'+window.location.hostname+'/newdir/newfile.html';\n".
"</script>\n");
This was not working and I tried to execute the code from the console and it works from there. I assumed it was something about timing, so I added a setTimeout to the redirect:
die("<script type='text/javascript' charset='utf-8'>\n".
"var configURL = 'http://'+window.location.hostname+'/newdir/newfile.html';\n".
"setTimeout('window.location.href = configURL', 500);\n".
"</script>\n");
This patch works for now but I think there should be a better way to do it.

javascript error on internet explorer 6,7,8, " is null or not an object "

when I start my index.php it calls my javascript file that has this code below:
when the application starts immediately this error appears:
and this can only happen on the internet explorers, there is no 'txtName' on index.php, because the. js is called for every page, there any way to improve this function ? tath i dont need to put manually the js in each page?
Anyone know how can I solve this ? Thank you very much...
Update:
After the updated question - you can test for the element first
function focus(){
var txtNameObj = document.getElementById('txtName');
if(txtNameObj){
txtNameObj.focus();
}
}
This should avoid the error with it not being defined.
Original
I can only guess there is one of two problems:
a.) Your DOM hasn't loaded yet (so even though that ID will exist, it doesn't yet)
b.) You do not have an element with that ID.
If the element does exist, be sure to only call the focus function once you are sure that the element is loaded. e.g. you could place it as a script tag just before the body close.
<script>
focus();
</script>
</body>
</html>
Why dont you put a conditional for this method:
In this case:
var iId = document.getElementById('txtName');
if(iId != null)
{
// Processing
}

javascript not being called

I am using this HTML
<html>
<head>
<Title>EBAY Search</title>
</head>
<script language="JavaScript" src="ajaxlib.js"></script>
<body>
Click here link to show content
<div id="Result"><The result will be fetched here></div>
</body>
</html>
With this Javascript
var xmlHttp
function GetEmployee()
{
xmlHttp=GetXmlHttpObject()
if(xmlHttp==null)
{
alert("Your browser is not supported")
}
var url="get_employee.php"
url=url+"cmd=GetEmployee"
url=url+"&sid="+Math.random()
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
function FetchComplete()
{
if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
document.getElementById("Result").innerHTML=xmlHttp.responseText
}
if(xmlHttp.readyState==1 || xmlHttp.readyState=="loading")
{
document.getElementById("Result").innerHTML="loading"
}
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
try
{
xmlHttp =new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
However it is not being called. get_employee.php works fine when I call it by itself, so that is not the problem. Is there anything wrong in my code that would prevent it from being called? I cannot test with any firefox extensions, I do not have access, so please don't give that as an answer.
edit: the problem is the javascript is not being called at all. I fixed the question mark problem, but even just a simple javascript with an alert is not being called.
use a javascript debugging tool like firebug, this will make your life simpler.
you had a syntax error in your code that made the error "GetEmployee is not defined"
it was a missing "catch" after the last try in "GetXmlHttpObject()". this is the same function after adding the missing "catch".
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
xmlHttp=new XMLHttpRequest();
}catch (e)
{
try
{
xmlHttp =new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
return xmlHttp;
}
var url="get_employee.php?"
Needs the "?".
It's better to use this markup to include your scripts:
<script type="text/javascript" src="ajaxlib.js"></script>
Change this
var url="get_employee.php"
url=url+"cmd=GetEmployee"
url=url+"&sid="+Math.random()
to this:
var url="get_employee.php?cmd=GetEmployee&sid="+Math.random();
You were missing the "?" and there's no need for all of the concatenation (but I guess that's just personal style).
Also, if you actually have the "<The result will be fetched here>" in your html, you should remove it.
I am a bit confused about putting the <script> tag into the no man's land between head and body. Does this have some special meaning?
Shouldn't there be a question mark or an ampersand between the getcommand.php and the cmd= parts?
I don't suppose its something silly like a missinq question mark in the url
var url="get_employee.php"
url=url+"cmd=GetEmployee"
url=url+"&sid="+Math.random()
I would have expected to see "?cmd=GetEmployee"
Make sure you aren't misplacing or naming a file.
You can change OnClick to all lowercase too.
var url="get_employee.php" + "?"
(answering the comment)
What error is reported? You still have to attach your FetchComplete function to xmlHttp's "onreadystatechange" property, but it shouldn't be an error not to do it.
Make sure that ajaxlib.js is really loaded, and that it is the file you mean. Put some alerts and see if they pop up.
If you can't use a proper debugger, you can add alert statements all over the place to see if anything is happening at all (yes, it's a bad solution, but anytime you don't use a good tool you have a bad solution).
Also, make sure the OnClick() returns false, to prevent the browser from reloading the page.
link
becomes
link
You can use alert(url) to check the exact url being sent.

Categories

Resources