Javascript following window.print(); not running in Firefox - javascript

I am attempting to print a form before it is submitted by a submit input control.
My code is
<input type="submit" name="printForm"
value="Print Application Form"
onClick="window.print();
if (submitting) {return false;}
else {submitting = true; return true;} ">
('submitting' a global 'var', initialised as 'false' - to stop double sends)
This works in Safari, Chrome and IE, but is giving a problem in Firefox - the form is not submitted after the printing completes - however, if the print dialog in Firefox is cancelled, the form is submitted.
I have tried moving the window.print into a function to isolate it. but that didn't change the result.
Any suggestions would be appreciated, thanks
I have searched here for anything related to window.print and scanned many questions without finding anything that helped. (I haven't read all of the thousands yet!)

I have found an answer ... in the original problem, the javascript was all being executed, but something in the window.print inhibited the actual send of the form.
The solution is to change the to button, and move the actual form submit into javascript, and position the submit to occur immediately before the window.print (instead of after!). In this way, both the form submit and the page print actually occur.

The issue could be in the form action. <form action="">
If you are loading a file on form submit then pass that file's complete path in the action instead of relative path.

Related

How would I save input from a text box and then move to the next page? (Javascript/HTML)

As part of my new job, I'm creating a small form where users answer a question and this is then saved and output at the end of the pages.
I started off with having a prompt where users were asked to explain their answers (which worked perfectly!), however I've been asked to change this to an input box.
Essentially the process I need to do is:
User enters in text box -> Clicks next button -> save input to session variable and move to next page
So far, I have the following HTML in the body:
<form name="next" action='#' method=post>
Explanation:<input type="text" id="xp" required><br>
<button class="nextButton" onclick="return explanation()">Next</button>
</form>
with the corresponding javascript:
function explanation() {
var exp = document.getElementById('xp').value;
sessionStorage.setItem("p1_reason", exp);
alert(exp);
document.location.href = 'page2.html';
}
So far the result of this is:
The text box is cleared, but nothing is saved or displayed onscreen
The next page is not displayed.
Any help/advice would be appreciated. I'm relatively new to js so I'd be grateful! I'm well aware that there are similar questions around, I just can't seem to see where I'm going wrong.
#David is right. You can add event.preventDefault() function to prevent the form from its default behaviour, which is submitting. Otherwise your code seems to work.
function explanation() {
event.preventDefault(); // <-- add here
var exp = document.getElementById('xp').value;
sessionStorage.setItem("p1_reason", exp);
alert(exp);
window.location.href = 'page2.html';
}
Also, don't use document.location.href, it's deprecated. It's better to use window.location.href instead.
When you click on nextButton, the browser run explanation() and then try to execute the action of your form. Because your action is action='#' it just try to reload the page, preventing document.location.href for working properly.
Actually, you can try to don't enter nothing on the box and click on the button. The redirect will work because the form is empty, so there is nothing to submit.

Getting Error "Form submission canceled because the form is not connected"

I have an old website with JQuery 1.7 which works correctly till two days ago. Suddenly some of my buttons do not work anymore and, after clicking on them, I get this warning in the console:
Form submission canceled because the form is not connected
The code behind the click is something like this:
this.handleExcelExporter = function(href, cols) {
var form = $('<form method="post"><input type="submit" /><input type="hidden" name="layout" /></form>').attr('action', href);
$('input[name="layout"]', form).val(JSON.stringify(cols));
$('input[type="submit"]', form).click();
}
It seems that Chrome 56 doesn't support this kind of code anymore. Isn't it? If yes my question is:
Why did this happened suddenly? Without any deprecation warning?
What is the workaround for this code?
Is there a way to force chrome (or other browsers) to work like before without changing any code?
P.S.
It doesn't work in the latest firefox version either (without any message). Also it does not work in IE 11.0 & Edge! (both without any message)
Quick answer : append the form to the body.
document.body.appendChild(form);
Or, if you're using jQuery as above
$(document.body).append(form);
Details :
According to the HTML standards, if the form is not associated to the browsing context(document), the form submission will be aborted.
HTML SPEC see 4.10.21.3.2
In Chrome 56, this spec was applied.
Chrome code diff see ## -347,9 +347,16 ##
P.S about your question #1. In my opinion, unlike ajax, form submission causes instant page move.
So, showing 'deprecated warning message' is almost impossible.
I also think it's unacceptable that this serious change is not included in the feature change list. Chrome 56 features - www.chromestatus.com/features#milestone%3D56
if you are seeing this error in React JS when you try to submit the form by pressing enter, make sure all your buttons in the form that do not submit the form have a type="button".
If you have only one button with type="submit" pressing Enter will submit the form as expected.
References:
https://dzello.com/blog/2017/02/19/demystifying-enter-key-submission-for-react-forms/
https://github.com/facebook/react/issues/2093
add attribute type="button" to the button on who's click you see the error, it worked for me.
alternatively include
event.preventDefault();
in your
handleSubmit(event) {
see https://facebook.github.io/react/docs/forms.html
I have found this problem in my React project.
The problem was,
I have set the button type 'submit'
I have set an onClick handler on the button
So, while clicking on the button, the onclick function is firing and the form is NOT submitting, and the console is printing -
Form submission canceled because the form is not connected
The simple fix is:
Use onSubmit handler on the form
Remove the onClick handler form the button itself, keep the type 'Submit'
You must ensure that the form is in the document. You can append the form to the body.
I see you are using jQuery for the form initialization.
When I try #KyungHun Jeon's answer, it doesn't work for me that use jQuery too.
So, I tried appending the form to the body by using the jQuery way:
$(document.body).append(form);
And it worked!
<button type="button">my button</button>
we have to add attribute above in our button element
A thing to look out for if you see this in React, is that the <form> still has to render in the DOM while it's submitting. i.e, this will fail
{ this.state.submitting ?
<div>Form is being submitted</div> :
<form onSubmit={()=>this.setState({submitting: true}) ...>
<button ...>
</form>
}
So when the form is submitted, state.submitting gets set and the "submitting..." message renders instead of the form, then this error happens.
Moving the form tag outside the conditional ensured that it was always there when needed, i.e.
<form onSubmit={...} ...>
{ this.state.submitting ?
<div>Form is being submitted</div> :
<button ...>
}
</form>
I faced the same issue in one of our implementation.
we were using jquery.forms.js. which is a forms plugin and available here. http://malsup.com/jquery/form/
we used the same answer provided above and pasted
$(document.body).append(form);
and it worked.Thanks.
I was able to get rid of the message by using adding the attribute type="button" to the button element in vue.
An example of Mike Ruhlin's answer, I was redirecting with react-router-dom Redirect on form submission.
Placing e.preventDefault() into my submit function removed the warning for me
const Form = () => {
const [submitted, setSubmitted] = useState(false);
const submit = e => {
e.preventDefault();
setSubmitted(true);
}
if (submitted) {
return <Redirect push to={links.redirectUrl} />
};
return (
<form onSubmit={e => submit(e)}>
...
</form>
);
};
export default Form;
Depending on the answer from KyungHun Jeon, but the appendChild expect a dom node, so add a index to jquery object to return the node:
document.body.appendChild(form[0])
Adding for posterity since this isn't chrome related but this was the first thread that showed up on google when searching for this form submission error.
In our case we attached a function to replace the current div html with a "loading" animation on submission - since it occurred before the form was submitted there was no longer any form or data to submit.
Very obvious error in retrospect but in case anyone ends up here it might save them some time in the future.
I have received this error in react.js. If you have a button in the form that you want to act like a button and not submit the form, you must give it type="button". Otherwise it tries to submit the form. I believe vaskort answered this with some documentation you can check out.
if using react and something like formik, the issue seems to be in the onClick handlers in the submit button
You can also solve it, by applying a single patch in the jquery-x.x.x.js just add after " try { rp; } catch (m) {}" line 1833 this code:
if (r instanceof HTMLFormElement &&! r.parentNode) {
r.style.display = "none"; document.body.append (r);
r [p] ();
}
This validates when a form is not part of the body and adds it.
I noticed that I was getting this error, because my HTML code did not have <body> tag.
Without a <body>, when document.body.appendChild(form); statement did not have a body object to append.
Your button has to be in the context of Form tag
button type="submit"
I was also facing the same issue , I removed onClick={onSubmit} form the button tag (I used Formik here)
I saw this message using angular, so i just took method="post" and action="" out, and the warning was gone.

Javascript Form Submit causing website to break

So I'm having an issue submitting a form. Basically once the form is submitted the entire site wont work until I clear the cash and refresh the browser.
The form tag is
<form action="cart.php" method="post" name="AutomaticReorderForm">
The form was initially being submitted like
function saveAutomaticReorder()
{
document.AutomaticReorderForm.action = "/store/save_automatic_order.php";
document.AutomaticReorderForm.submit();
}
which has a javascript call to this function in the href of the button.
I tried jquery like so
$("#saveAutomaticReorder").click(function() {
$('form[name="AutomaticReorderForm"]').attr("action", "/store/save_automatic_order.php");
$('form[name="AutomaticReorderForm"]').submit();
});
These both submit the form fine. In the php page at the very top i put in die(); which killed the page before any php was run but then it still gave me the same problem of breaking the whole site. Im not sure where to go from here does anyone have an idea about what could be causing this issue? Thanks

IE 11 cannot submit an HTML form

I have this HTML form
<form name="nextform" action="anotherpage.php" method="post" enctype="multipart/form-data">
<input name="pinid" id="pinid" type="hidden">
<input type="submit" name="submit" id="post" value="Lets Go" class="formButtonMap">
</form>
pinid dynamically gets a value using JavaScript. When it gets a value I alert it and it works.
But, when I click the Lets Go button, nothing happens. I see the Internet Explorer loading for a couple of minutes and then I get the message “The webpage does not respond”. If I hit refresh it goes to anotherpage.php but the values from the form did not arrive to the server.
Rarely shows this message:
Visual Studio Just-In-Time Debugger
An unhandled win32 exception occured in iexplorer.exe [688]
Possible Debuggers :
New Instance of Microsoft Visual Studio 2012
This behavior is observed only in Internet Explorer 11.0.2. The form works in older versions of Internet Explorer and also in Chrome and Firefox. I get no errors in IE’s console.
Here is the JavaScript code, placed above the form:
// called when another button is clicked - basicaly is websockets
function save() {
var so = new WebSocket("ws://localhost:8000");
so.onerror = function (evt) {
alert('problem');
}
if (sara == 'LINES') {
so.onopen = function() {
so.send(JSON.stringify({
command: 'insertAll',
name: document.getElementById('name').value
}));
}
}
if (sara == 'POLY') {
so.onopen = function() {
so.send(JSON.stringify({
command: 'insertHalf',
name: document.getElementById('name').value
}));
}
}
so.onmessage = function (evt) {
var received_msg = evt.data;
document.getElementById("next").style.display = "block";
document.getElementById("name").value = "";
document.getElementById("descr").value = "";
clearLinks();
document.getElementById("pinid").value = received_msg;
alert(document.getElementById("pinid").value); // works
so.close();
}
}
I tried to edit the code using document.getElementById("nextform").submit();, problem is still there.
Is it me? Is it a bug? What am I missing?
I believe this is a bug when setting form values to empty in IE.
IE Bug Report
I would suggest trying a different method to resetting the form values, I have used this method in the past:
document.getElementById('name').parentNode.innerHTML = '';
Maybe not your issue, but:
<input type="submit" name="submit" ... >
Giving a form control a name of submit will replace the form's submit method with a reference to the control, so calling form.submit() will attempt to "call" the input.
hi might be problem in your code you miss to add id in form and you try to access form by it's id that you not define.
document.getElementById("nextform").submit();
its required
<form name="nextform" id="nextform" action="anotherpage.php" method="post" enctype="multipart/form-data">
...
...
...
</form>
Trace through what happens in the anotherpage.php page when it receives the postback, evt.data might not be encoded as you expect (is it binary or text, if text, is it utf-8).
Postback to a different page where all it does is output the posted back values.
Does the socket close throw an exception?
so.close();
My original code has a form with more than 5 fields. When submitted calls the save(). save() function also clears the fields using JS.
There is a bug in IE11, that crashes the browser if you try to clear more than 5 fields , using JS. See here , there is workaround.
That bug crashes the first form, then the nextform form and also the browser. I APOLOGISE for not posting all my code, I did not know it had to do with the first form.
Because I thought the same piece of code had two different problems , I posted another question, very similar , here
In my case the input button had the same ID and NAME. So you can check if they are the same and if indeed they are the same use different value for one of the parameters.
I hope it helps.

Jquery form submit works only once

I am making a webpage showing the frequency of searches for some searchterms in a table. Above that table are 2 radio buttons that enables the user to select if he wants to see distinct search results or all results.
When using this javascript:
$(function() {
$('.distinct_radio').change(function() {
console.log("submit distinct_radio");
this.form.submit();
});
});
It works fine. I can toggle over and over again, switching table values correctly. However, if I use this javascript:
$(function() {
$('.distinct_radio').change(function() {
console.log("submit distinct_radio");
$('form#searchTermForm').submit();
});
});
The form is defined as
<form id="searchTermForm" action="/searchterms.php" method="POST">
<div class="configDiv">
<input name="distinct" id="radio-choice-v-2a" class="distinct_radio" value="false" <?php if (strcmp($distinct, "false") == 0) {echo "checked=\"checked\"";}?> type="radio">
<label for="radio-choice-v-2a">Show total number of searches.</label>
<input name="distinct" id="radio-choice-v-2b" class="distinct_radio" value="true" <?php if (strcmp($distinct, "true") == 0) {echo "checked=\"checked\"";}?> type="radio">
<label for="radio-choice-v-2b">Show number of different people</label>
</div>
</form>
Some relevant php:
<?php
if(isset($_POST['distinct'])){
$distinct = $_POST['distinct'];
} else {
$distinct = "false";
}
?>
Javascript that I am using:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="js/custom.js"></script>
<script type="text/javascript" src="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.js"></script>
Updating this to jquery mobile 1.3.1 does not resolve the issue.
It works fine the first time clicking the radio button. After that, no response at all. If I manually refresh the page, it works for one time again.
With the first script, the message "submit distinct_radio" is printed on the console, and that the console is cleared by the submission itself.
With the second script, the message "submit distinct_radio" is printed on the console, but the console is not cleared. It prints that message, and the POST request being done. However, the POST request is really done and the web page is updated correctly. Clicking again does not result in any message printed at the console, nor any request done.
With the second script, if I change the path after "action" to some non-existent one, a console message is printed every click, accompanied by a new attempt to do a POST request to the non-existing location.
I face this problem in FireFox, Chrome and Opera.
Next to curiosity, I want to use this to submit the form when the user clicks on the table header to sort. From there, I cannot use "this.form.submit();"
How can this behavior be explained?
Edit:
Thanks to #peddle (See answer below):
Seems some issue in Jquery Mobile. Deleting the reference to jquery.mobile-1.3.0.min.js makes it work over and over again (hence very ugly). Javascript references are like suggested at http://jquerymobile.com/blog/2013/04/10/announcing-jquery-mobile-1-3-1/ , so jqm 1.3.1 and jquery 1.9.1 are meant to cooperate.
This is not an answer but required more space than a comment, have you tried the following to see if it makes any difference:
$(function(){
$('.distinct_radio').change(function() {
console.log("submit distinct_radio");
$('form#searchTermForm').get(0).submit();
});
});
The former of your examples is using pure JavaScript to submit the form and the latter is using jQuery's version of submit. The above uses jQuery to find the form, but should use the JavaScript submit method. The above should test the following:
If the above works without problem then your issue is with jQuery's submit.
If the above fails, but produces a undefined object error, then jQuery can't find the form.
If the above fails but without error you have something very odd happening, or the JavaScript is not being evaluated for some reason.
update
Another thing to try:
$(function(){
$('.distinct_radio').change(function() {
console.log("submit distinct_radio");
$('form#searchTermForm').trigger('submit');
});
});
Now I would expect the above to have the same problem as $().submit() but you never know. Another thing that is possibly causing an issue is that you don't seem to have a submit button in your form markup. Whilst logically this shouldn't have any bearing on the situation, if you read through the jQuery .submit page they have this quote:
http://api.jquery.com/submit/
Depending on the browser, the Enter key may only cause a form submission if the form has exactly one text field, or only when there is a submit button present. The interface should not rely on a particular behavior for this key unless the issue is forced by observing the keypress event for presses of the Enter key.
Whilst the above is only talking about using the enter key, it is possible that browsers/jQuery have other oddities/differences laying about when submit buttons are missing.. I am reaching however.
Beyond the above it is possible there is some interference between jQuery and jQuery Mobile (your specific version), or it could be a bug in jQuery 1.9.1 (I can't say I've used this much in production). If you investigate the source of the $().trigger() method, which is used when using $().submit(), you'll see it's doing a lot of "magic" — which is why it's probably better to use the pure JavaScript method when you can get your hands on it.

Categories

Resources