How do I catch a form submit in Javascript onload? - javascript

I have a 3rd party system, where I can add articles (with (raw) html). One page contains a search form, which does a post to itself. Upon load (after post) it will add a javascript submit form using javascript - e.g.
function redir() {
document.myform.submit();
}
.... //some other stuff here
redir();
I'll not go into details on the design (I know why it is designed this way but cannot change it - its crappy design, I know!).
Is there someway to catch this "onload" submit?
I have tried this:
var sform = document.getElementsByName('myform');
try {
sform.addEventListener("submit", alert('Gotcha!'));
} catch(e) {
sform.attachEvent("submit", alert('Gotcha!')); //Internet Explorer
}
Also jQuery:
$('myform').submit(function() {
alert('Gotcha!');
return false;
});
I cannot seem to catch the event. I can override the method:
redir = function(){
//Empty - override
}
...but the submit action is trigged before my script is loaded or it will override my overridding method.
I hope this makes sense.

Your jQuery was close. You just need to use a # before your id based selector, just like in CSS.
$('#myform').submit(function() {
alert('Gotcha!');
return false;
});

Did you override the function in the correct place? The following works for me and stops the submit.
function redir() {
document.myform.submit();
}
redir = function(){}
redir();
Demo

Related

if confirm ignores location.href

The following code reloads the page rather than the desired URL
function delFile(name,id) {
if (confirm('Are you sure you want to DELETE '+name+'?')) {
location.href='/cgi-bin/cnc.cgi?phrsrg~038919718485478~'+id ;
alert('/cgi-bin/cnc.cgi?phrsrg~038919718485478~'+id);
}
else {
return false;
}
}
In the alert, the id is shown as being added properly and the URL is correct. I can copy it from the alert, then use that text to get the right result. Other scripts on the same page that use similar location.href are working perfectly but this is the only one using confirm.
I've also tried
window.location.href = "http://stackoverflow.com";
But the page still reloads.
The triggering link is:
onClick="return delFile('Bill','1234')
The href on the triggering link is still being linked to, because delFile() only returns false if the confirm is not accepted -- that's what's causing the page reload. When the function returns true, the link fires before the redirect occurs.
You want the function to return false in all cases, so don't put the return in an else clause.
function delFile(name, id) {
if (confirm('Are you sure you want to DELETE ' + name + '?')) {
location.href = '/cgi-bin/cnc.cgi?phrsrg~038919718485478~' + id;
alert('/cgi-bin/cnc.cgi?phrsrg~038919718485478~' + id);
}
return false; // always, since you always want to prevent the link's default behavior. (Could also use event.preventDefault here.)
}
test
function delFile(name,id){
if (confirm('Are you sure you want to DELETE '+name+'?')) {
/* var fullpath = better to use the full url name/link;*/
var url = '/cgi-bin/cnc.cgi?phrsrg~038919718485478~'+id;
window.open(url, '_parent');
alert('/cgi-bin/cnc.cgi?phrsrg~038919718485478~'+id);
}
else {
return false;
}
}
It looks like the delFile() function is missing the opening curly brace, so I would start by fixing that. If the issue persists, check the JS console. Also, posting a codepen would be helpful.

javascript error when accessing flash redirect attribute (thymeleaf, springmvc)

I'm currently stuck with the following problem with SpringMVC, Thymeleaf and Javascript.
1) Server-Side: Under some circumstances I add a flash redirect attribute in my controller before redirecting to a certain page.
redirectAttributes.addFlashAttribute("myCondition", true);
2) Client-Side: In case that attribute exists, I want my javascript function to execute additional code.
window.onload = function() {
...
if([[${myCondition}]]) {
//do something
}
}
This works fine after the redirect, but on first enter the redirect attribute does simply not exist, which results in the following javascript code being rendered:
window.onload = function() {
if() {
//do something
}
}
This code is not valid and therefore produces a javascript error.
I'm not sure how to check with javascript if the redirect attribute exists?
can you try the following code and let me know if this works for you
declare a variable mycondition
var mycondition = [[${myCondition}]];
if(mycondition) {
//do something
}
Hope this helps

Catching A Browser Close Event

Hello Seniors (As I am new to Web Based Applications),
I was keen to implement or catching browser closing event.
Yes! I did it and successfully implemented it by using javascript{see code below}
but I have implemented it in a web page without MasterPage.
Now, as I am trying to implement it in a webpage with MASTERPAGE but in each post back...the event window.onunload is caught, which is giving me problems...
Is there any technique or logic to detect whether I can differentiate between a Close browser button and a page's post back event.
Please guide me...as I have to implement in a project as soon as possible....
thank you.
Ankit Srivastava
<script type="text/javascript">
function callAjax(webUrl, queryString)
{
var xmlHttpObject = null;
try
{
// Firefox, Opera 8.0+, Safari...
xmlHttpObject = new XMLHttpRequest();
}
catch(ex)
{
// Internet Explorer...
try
{
xmlHttpObject = new ActiveXObject('Msxml2.XMLHTTP');
}
catch(ex)
{
xmlHttpObject = new ActiveXObject('Microsoft.XMLHTTP');
}
}
if ( xmlHttpObject == null )
{
window.alert('AJAX is not available in this browser');
return;
}
xmlHttpObject.open("GET", webUrl + queryString, false);
xmlHttpObject.send();
return xmlText;
}
</script>
<script type="text/javascript">
var g_isPostBack = false;
window.onbeforeunload = check ()
function check()
{
if ( g_isPostBack == true )
return;
var closeMessage =
'You are exiting this page.\n' +
'If you have made changes without saving, your changes will be lost.\n' +
'Are you sure that you want to exit?';
if ( window.event )
{
// IE only...
window.event.returnValue = closeMessage;
}
else
{
// Other browsers...
return closeMessage;
}
g_isPostBack = false;
}
window.onunload = function ()
{
if ( g_isPostBack == true )
return;
var webUrl = 'LogOff.aspx';
var queryString = '?LogoffDatabase=Y&UserID=' + '<%# Session["loginId"] %>';
var returnCode = callAjax(webUrl, queryString);
}
</script>
There is no javascript event which differentiates between a browser being closed and the user navigating to another page (either via the back/forward button, or clicking a link, or any other navigation method). You can only tell when the current page is being unloaded. Having said that, I'm not sure why you'd even need to know the difference? Sounds like an XY problem to me.
The answer can be found on SO:
How to capture the browser window close event?
jQuery(window).bind("beforeunload", function(){return confirm("Do you really want to close?") })
and to prevent from confirming on submits:
jQuery('form').submit(function() {
jQuery(window).unbind("beforeunload");
...
});
First step: add global JavaScript variable called "_buttonClicked" which is initially set to false.
Second step: have every button click assign _buttonClicked value to true.. with jQuery it's one line, pure JavaScript is also few lines only.
Third step: in your function check _buttonClicked and if it's true, don't do anything.
EDIT: After quick look in your code I see you already have steps #1 and #3, so all you need is the second step, assign g_isPostBack as true when any submit button is clicked. Let me know if you need help implementing the code and if you can have jQuery.
If one wants to catch Log out when the browser is closed (by clicking on the cross), we can take the help of window events.
Two events will be helpful: onunload and onbeforeunload.
But the problem arises that the code will also work if you are navigating from one page to another as well as also when one
refreshes the page. We don't want our sessions to be clear and inserting the record of logging out while refreshing.
So the solution is if we distinguish the difference between closing and refreshing or navigating.
I got the solution:
Write 'onbeforeunload ="loadOut();"' within the body tag on master page.
Add the following function inside script in head section of master page :-
function loadOut() {
if ((window.event.clientX < 0) || (window.event.clientY < 0))
{
// calling the code behind method for inserting the log out into database
}
}
And its done. It is working for IE, please check for other browsers. Similarly you can detect the event if the window is closed
by pressing the combination of keys ALT+F4.
window.unload fires when we navigate from one page to another as well as when we click on close button of our browser,So to detect only browser close button you need to use flag.
var inFormOrLink;
$("a,:button,:submit").click(function () { inFormOrLink = true; });
$(":text").keydown(function (e) {
if (e.keyCode == 13) {
inFormOrLink = true;
}
})/// Sometime we submit form on pressing enter
$(window).bind("unload", function () {
if (!inFormOrLink) {
$.ajax({
type: 'POST',
async: false,
url: '/Account/Update/'
});
}
})

Firefox 3.6 - location.href not working in JSP

I have JSP page with method = POST and action='/mydir/mypage/nextpage'
I have a button:
<button title='Continue' onclick="this.form.perform.value='cancelButton'; javascript:doCloseWindow();">Continue</button>
and JavaScript method like:
function doCloseWindow(){
location.href = "https://abc.xyz.com/mydir/?param=123";
}
It does not work in Firefox 3.6. On click of button; it redirects to the path I mentioned in form action.
With Tamper data I find that the request goes to URL (as in method) with GET and then it redirects to form's action URL.
I added return false in the method call also -- javascript:doCloseWindow();return false
I tired various combinations like
window.location.href = "https://abc.xyz.com/mydir/?param=123";
window.document.location.href = "https://abc.xyz.com/mydir/?param=123";
document.location.href = "https://abc.xyz.com/mydir/?param=123";
But no success.
Remove the "javascript:" before the call to doCloseWindow.
At this point, you've already executed some JavaScript code in this event handler — it doesn't make sense to try to tell the browser again that the following code is JavaScript.
Try changing your Javascript call to:
function doCloseWindow(){
alert('here');
location.href = "https://abc.xyz.com/mydir/?param=123";
return false;
}
I'm wondering if the function is actually running.

Detecting/handling changed data in ASP.NET MVC / jQuery / JS

We need to universally handle changed data on forms in ASP.NET MVC. Our application has ~100 forms, and the user should be prompted if they start editing a form and click on anything other than Save (i.e. something like "Your data has been changed. Click OK to return to the form, or Cancel to lose all changes.").
It looks like SO implements this (while asking a question) using JavaScript. In general, is this the best way? Also, any tips on how best to implement this?
The way I've done this is to use javascript to store the initial values of inputs when the page loads. Then I have a beforeunload handler that checks to see if any of the inputs have a different value than when the page was loaded. If any inputs are changed, it prompts the user to confirm that they want to leave the page, canceling the action if they cancel. In my submit logic, I set a flag that keeps the beforeunload check from happening so a submit doesn't get the prompt.
I suspect there is a jQuery plugin to do this, but I haven't implemented this since I started using jQuery. My earlier code used Prototype.
Edit: Couldn't find a jQuery plugin, but I could have just missed it. Here's a sample of how I might do it. Obviously, there's more that could be done. Note I wasn't able to get it to work with pure jQuery -- not sure exactly why, the popup would appear twice.
This should work with all input elements. You might want to change it to ignore/handle buttons, though. I only adjusted it to ignore a submit button (so it can post back without the popup). If other button types can cause a page unload, you may need to address that.
var CheckOnClose = function() {
this.initialize();
}
CheckOnClose.prototype = {
submitting: false,
initialize: function() {
var that = this;
window.onbeforeunload = function() { return that.checkLeavePage(); }
},
isChanged: function() {
var changed = false;
$('input:not(:submit)').each( function() {
var iv = $(this).data('initialValue');
if ($(this).val() != iv) {
changed = true;
return false;
}
});
return changed;
},
setSubmitting: function() {
this.submitting = true;
},
checkLeavePage: function() {
if (!this.submitting && this.isChanged()) {
return 'You have some unsaved changes.';
}
}
}
var checker = new CheckOnClose();
$(document).ready(function() {
$(':input:not(:submit)').each( function() {
$(this).data('initialValue',$(this).val() );
});
$(':submit').click( function() {
checker.setSubmitting();
});
});
JavaScript is your only shot for doing this. It doesn't even have to be a complicated bunch of code. All you have to do is have a global variable to flag if the form is in editing stages (var formEdited = false; would do), and then add this snippet to your page:
window.onbeforeunload = confirmExit;
function confirmExit()
{
if (formEdited)
{
return "You have attempted to leave this page. If you have made any changes to the fields without Submitting the form, your changes will be lost. Are you sure you want to exit this page?";
}
// no changes - return nothing
}

Categories

Resources