What is wrong with document.forms[0].submit()? - javascript

I am helping someone with a web page that they are having a problem with, I sorted out the validation part but behavior of the submit process is not as you would expect.
To catch and stop the default event, I used the following in the head of the function
var evt = event ? event:window.event;
if (evt.preventDefault) evt.preventDefault();
evt.returnValue = false;
evt.cancelBubble = true;
If I change any part of it, the prevention of the default action doesn't work and the page in MSIE will submit even when validation errors exist or persist. Under Chrome the browser does not submit but throws an error, with the prevent routine under MSIE the debug show up an error in the same line.
Chrome: Uncaught TypeError: object is not a function
MSIE : Object doesn't support this property or method
The line in question :
document.forms[0].submit();
Trying
document.forms.form1.submit();
// or
document.forms['form1'].submit();
doesn't work however
document.forms.form1.reset();
or any of the variants of addressing, including the .getEmelentsById("..."); method works fine, I am just stumped as to the problem, the thought that my JS Interpreter is stuffed up did cross my mind...
Anyone got any ideas that DOES NOT use JQuery please.

Since form.reset() does work, but form.submit() does not, something is overwriting the submit method on the form. I bet you have a form element with an id or name of "submit":
<input id="submit" />
Or:
<input name="submit" />
That way form.submit would resolve to the input element, rather than the form's submit() method.
Quick jsFiddle demo
The easy fix is to change the id of the element. The harder, less sensible, fix would be to get a reference to the prototype submit method and call it in the context of your form:
var f = document.forms.form1;
Object.getPrototypeOf(f).submit.call(f);
or
document.createElement("form").submit.call(document.forms.form1);

Related

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

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.

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.

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.

CKEditor submitting empty content to the form.

I've started using CKEditor v3 few weeks ago.using it in a php project.i've been using it with jquery (using jquery adapter) and all this while using $.ajax (because can't handle for errors when using jquery form) to submit and i thought everything was alright .
So here pops up a case where i need to use normal form mechanism to submit the ckeditor content and all the other information of the form.
To my surprise the content was empty so i started google and apparently it's a known issue.
i haven't seen any thing YET that could let me post my content to php side. so i've come up with a workaround.
I know onclick will always fire before the onsubmit so i've written this.
function returntoSubmit(){
myForm = document.forms[0];
myForm.elements["content"].value = $("#content").val();// note that the textarea name and id are all the same "content"
}
// html here
<input type="submit" value="Save" onclick="returntoSubmit()" />
that does the work for me.But truly and a little uncomfortable with this, isn't there any better method to solve this issue?
Thanks
I'm running a large application with some nasty legacy code and needed something that worked across the whole app as non-intrusively as possible. In my case it wasn't feasible to listen for submits on each page individually, and even when I did I occasionally had race conditions where the submit still occurred before the click event code had a chance to do it's thing. The following seems to do the trick for me when ran after page load at a global scope:
for(var i in CKEDITOR.instances) {
CKEDITOR.instances[i].on('blur', function() { this.updateElement(); });
}
May this help
CKEDITOR.instances[content].getData()
Just ran across this problem too... it seems that the best way to update all the textareas is:
for(var i in CKEDITOR.instances) CKEDITOR.instances[i].updateElement();
http://cksource.com/forums/viewtopic.php?f=11&t=15877
I have actually added my own twist that works nicely as I was having trouble today with the same issue.
I used your function call, but instead do this i give my textarea the ID of ckeditor:
function returnToSubmit() {
$('#ckeditor').val(CKEDITOR.instances['ckeditor'].getData();
}
I used this in a jquery ready event for all forms:
$('form').on('submit',function(){
for(var i in CKEDITOR.instances) {
CKEDITOR.instances[i].updateElement();
}
});
Later I add another specific form submit event handler to do the actual custom submit logic for each form.

Categories

Resources