Jquery form submit works only once - javascript

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.

Related

Form Submit not working in latest chrome build (83)

Chrome : chrome update Version 83.0.4103.97 (Official Build) (64-bit)
Flow
Function function_name is called from a page (this page remains the main parent page in the whole scenario) which has a table with multiple records and a record has a hyperlink which fetches more data and displays in an overlay/popup.
The code etc. mentioned in the code section in the bottom is on that Popup/Overlay piece where form & iframe exist and facilitate the whole process.
On Form submit here another piece of html code is called which is then populated in iframe, please check the target of the iframe.
Issue
The form submit was working earlier for all browsers and post new update it's not
working on latest chrome build but it is working on other browsers at the moment without any issue.
Explanation of not working
I have added logs, it works as expected till form submit line is called. On Form submit we expect the new html piece to be called and then that to be loaded in the iframe. That page never gets invoked on the latest chrome build (does get invoked in all other browsers), there is no reflection on network tab either which should happen because on form submit another file is called. (happens in all other cases)
Observations
The popup flow is initiated from a button click in parent page (as explained in the flow)
< a href="#" onclick="function(this,val1,val2); return false;">
The code for the same is given above, if the same piece of code is removed from the parent page and then replaced with something else and then again changed back to this same code then it works normally. (I have no clue why!)
The behavior is erratic too, once in a blue moon even on latest chrome it works properly, once or twice. But the efficiency of system on all other browsers is 100%.
Code : Minimal (Comments are added for understanding separately)
<div id="divid" class="dialog" title="">
<!-- Iframe -->
<center>
<iframe name="frameid" id="frameid" src="/images/somegif.gif" width=820 height=400 frameborder=0 style="border:0; padding:0; margin:0;"></iframe>
</center>
</div>
<!-- Form -->
<form id="formid" name="formid" method="post" action="/somefile.html" target="framename">
<!-- Some Form Elements -->
</form>
<script>
//Javascript
$(function() {
$("#divid").dialog({
width: 860,
autoOpen: false,
modal: true,
resizable: false,
open: function(e, ui) {
$(this).siblings(".ui-dialog-titlebar").find("button").blur();
},
close: function() {
jQuery('#framename').attr('src','/images/somegif.gif')
}
});
});
function function_name(val1,val2) {
var form_obj;
form_obj=document.getElementById('formid');
if (form_obj) {
//some operation, validation etc.
jQuery("#divid").dialog('open');
somefun(form_obj, "var_name", var_name); //They are working fine
somefun2(form_obj, "var_name2", var_name2); //They are working fine
form_obj.submit();
}
}
</script>
I just noticed that form name and id is same, same goes for the iframe. The developer who wrote this is not with us anymore, in short, not my code.
#Gandalf, found this issue on chromium.
Issue 1092200: Submitting form whose target is an iframe randomly fail siliently
A bug fix for it was merged into 84, but a bugfix for Issue 1092313: Form submission takes precedence over window.location navigation
caused a regression, and looks like they are still looking into it..
We are also experiencing the same problem, and watching 1092200

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.

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.

Using jQuery validate plugin: onfocusout, onkeyup notworking as expected on production site

I am using jQuery Validate plugin v.1.9.0 it works very nicely. But I am facing this issue, once the user submits the form & if there are any errors, it correctly display error message. The problem is that it does not update the message if the user takes an action to remedy that error. E.g. if a field is required, upon getting the message the first time, user starts typing, then that message should go away.
In the docs it mentions that onfocusout & onkeyup are used for this purpose & by default they are set to true. The funny thing is it seems to work on my local workstation but it fails (silently) once I upload my code to production site. I thought I was messing it up royally somehow so I fired up jsfiddle and put relevant code to see if it happens there as well.
I was amazed to see it happens there as well. So my question is why does it work on my local machine but not on production sites?
P.S. Self-contained example at http://jsfiddle.net/tankchintan/cge44/5/
UPDATE
To replicate the issue, do -
Go to the jsfiddle page.
Without filling out any fields hit submit the form.
It will show error message besides each field.
Now start typing in any one of the fields.
You will notice that the error message doesnt go away, even though the rule is satisfied. On my local machine that error mesaage does go away, once I type anything in the field.
Use this instead!
onkeyup: function(element) { $(element).valid(); },
onfocusout: function(element) { $(element).valid(); },
This problem even exists in some of the examples on the JQuery website.
I found that the problem occurs when the input element has no type. Web browsers assume that the type is "text" if not specified, but jquery.validate has a problem with that. Your input element should look like this:
<input id="cname" name="name" type="text" class="required" minlength="2" />
Apparently this doesn't work if your jQuery library is too new. I was experiencing the same thing, rolling back from jquery v1.7.2 to v1.3.2 fixed the problem.
The example page at http://jquery.bassistance.de/validate/demo/ uses 1.3.2, but I'm not sure which specific version of jquery this breakage occurred in.
The following works for me:
$(document).ready(function () {
$("#myFormElement").submit(function (event) {
var validator = $.data($('form')[0], 'validator');
validator.settings.onfocusout = function (element) { $(element).valid(); };
validator.settings.onkeyup = function (element) { $(element).valid(); };
});
var validator = $.data($('form')[0], 'validator');
validator.settings.onfocusout = false;
validator.settings.onkeyup = false;
});
This disables initial onkeyup validation. If the user then clicks submit, we re-enable validation so that once the field is valid, he/she is given immediate feedback.
I'm not sure why these properties are boolean initially and then callbacks on the submit event. I only found the method by setting the properties to true in the submit event, which caused an exception in the validation library (was attempting the call function).
I think the default behaviour is to only hide that message when the field validates e.g. 'Please enter a valid email address' disappears after you enter 'foo#example.com', which I think makes sense.
See demos: http://jquery.bassistance.de/validate/demo/
I think you might be trying to do something similar to this: jquery validate: focusCleanup: true and focusInvalid: false don't work as expected

simple jquery event handler

having some real problems with jquery at the moment. Basically what I have so far is. The form is submitted once the form is submitted a grey box pop's up with the relevant infomation.
What I need to do though is refresh the whole page then allow the grey box to appear.
I have the following code
$("#ex1Act").submit(function() {
//$('#example1').load('index.php', function()
$("#example1").gbxShow();
return true;
});
the line which is commented out load's the page again after the form is submitted the other code makes the grey box pop-up.
Is their a way to say once the:
$('#example1').load('index.php', function()
has been exucted do this:
$("#example1").gbxShow();
hope this makes sense.
This is not possible.
Once the form is submitted, the Javascript running on the page that submitted the form is completely gone; it cannot affect the page that the form returns.
Instead, you should put server-side code in the form that writes $("#example1").gbxShow(); in a separate <script> block if the form has been submitted.
Why not just submit the form normally (i.e., not using JavaScript) and add a variable to the resulting page signalling the need to display the grey box? Like so:
<?php if(isset($_POST['submit'])): ?>
<script type="text/javascript">
var showGreyBox = true;
</script>
<?php endif; ?>
...
<script type="text/javascript">
$(function(){
if(showGreyBox !== undefined){
// execute code to show the grey box
}
});
</script>
Something like that, maybe?
The problem you have is that the web page is "stateless". This means that you can't do a bit of JavaScript, refresh the page and continue on with your JavaScript. When you refresh the page, you lose your current state and the page starts from scratch.
You will need to re-engineer your design to bear in mind the page lifecycle (i.e. all JavaScript stops permanently on navigation).
One solution may be to use the jQuery AJAX forms plugin, which will submit the form to the server and give you back the result of the submission, which would avoid breaking the page lifecycle. You could then display the box as you wish.
The standard way to do this is to have the server return the gray box contents in the response to the form post.
You could probably do this in jquery by putting the page and the grey box into separate iFrames so that it would be safe from the page refresh

Categories

Resources