I'm new here in terms of asking questions, but I have read many articles/questions/answers for quite some time now. My question is about part of a code that got me stuck for some time now.
So in my project I've got a registration form that has an JS validation and server side validation. Now what I wanted to do is disable form submitting before the JS validation is ok and I've set some conditions for it to be like that. Now the problem occured when those conditions were met. I used this line to stop form from submiting:
$('.memberReg').on('submit',function(){return false;});
In a situation like this for instance:
if(response.okText == 'SUCCESS' && response.warning == null )
{
$('label[for="email"]').addClass("success");
$('label[for="email"]').append("<span> is not yet registered!</span>");
console.log(result);
}else
{
$('label[for="email"]').addClass("error");
$('label[for="email"]').append("<span> is already taken!</span>");
$('.memberReg').on('submit',function(){return false;});
}
What happens here is that I do block the form from submiting, but it is blocked entirely, even when the other conditions are met. In this example even with correct email you cannot submit anymore.
I have tried using a variable with true-false statements that would make a validForm() function submit the form, but the function starts looping and it is still not enabling the form.
I also tried using return true for the form submit in the valid email part, still the same effect.
Anyone knows how to block it only on a certain condition without blocking it entirely so that the user has to refresh if he wants to send?
I believe I figured it out, after a few test runs it works smoothly, so I will post it in case someone else might have the same problem.
So at start I used:
$('.memberReg').on('submit',function(){return false;});
Which was overwriting the submit handler as one of the good people told me in one of his answers. So I tried changing my approach to the way I want to implement it and used:
$( ".memeberReg" ).submit(function( event ) {
if ( condition ) {
//successfulValidationCode
return;
}
//errorCode
event.preventDefault();
})
Under conditions I am checking the variables that I set in my field validations and in case of a bad input i use event.preventDefault(); to block the form again.
The problem is that you're overwriting the submit handler, and once it is overwritten, it is gone until the page is reloaded. I would question this approach entirely to be honest; you shouldn't have to overwrite the submit handler to prevent the form being submitted.
By the way, you're using JavaScript validation, not AJAX validation. AJAX is the process of sending a request to the server, and potentially receiving a result, without refreshing the page
Related
I've got a JavaScript function that submits a form.
The first step of my function is to disable it (to prevent multiple clicks) and apply a class that better illustrates that it's disabled. I also change the text to 'Please Wait...'
The next step is to validate my form. If validation fails, revert the changes in the first step, to return the button to its normal state.
If validation passes, submit the form.
This all essentially happens in the same process.
What I find is happening, is that in Safari, the first stage of the process (the button styles) is all but ignored. Upon further digging, I realised that it is working but the UI isn't redrawing until after the process completes. The problem here is that the completion of the process is a redirect away from the page, so the user never gets to see 'Please wait...'
Then I explored why Safari isn't redrawing the UI and I discovered a number of fixes for this, one such example is below:
// Aims to trigger the redraw by 'resetting' it
elem.style.display='none';
elem.offsetHeight;
elem.style.display='';
Another one I tried was deliberately hiding and showing the element before/after the update utilising Prototype (which is the primary JavaScript library on the system):
elem.hide();
elem.addClassName('disabledBtn');
elem.disable();
elem.update('Please Wait');
elem.show();
Another was to create a 'redraw' method to force a redraw.
Element.addMethods({
redraw: function(element){
element = $(element);
var n = document.createTextNode(' ');
element.appendChild(n);
(function(){n.parentNode.removeChild(n)}).defer();
return element;
}
});
...
elem.addClassName('disabledBtn');
elem.disable();
elem.update('Please Wait');
elem.redraw();
None of these items will work. The process will not update the UI until after the completion, and the user has redirected away. For reference, this is a pretty intensive form with a good few seconds of processing required during its submission, so this is a UX nightmare.
Has anybody else come across this situation?
I've figured this out.
As this is technically a workaround, rather than a solution to the problem, I'd still be open to other answers that may solve the issue outright.
I thought about this 'process' terminology, and how I could effectively end the process - thereby applying the styles, and start another one to submit the form.
The way I figured this out was to take the final stage of my code (the form submission) and push it into an asynchronous process. This way, the styling and validation 'process' will complete, with the style changes taking effect immediately, and the form submission will happen at some point after this.
I managed this asynchronous process with setTimeout()
elem.observe('click', function(e) {
// [Disabled styles]
// [Form Validity]
if (!valid) {
// [Reverse Button Disabling]
} else {
setTimeout(function(){ $('myform').submit(); }, 0);
}
});
Have you tried stopping the event first (in case your button is an actual type="submit")? i.e.
elem.observe('click', function(e) {
e.stop(); // prevent the default actions
// [Disabled styles]
// [Form Validity]
if (!valid) {
// [Reverse Button Disabling]
} else {
$('myform').submit();
}
});
I have a code to preventDefault after a form submit, and act accordingly to different conditions. Both condition work, everything works, but after the ELSE condition, the page refreshes. Here is the code:
$('.form_invitation').on 'submit', (e) ->
e.preventDefault()
$('#sending_invite').show()
$.post $(this).prop('action'), $(this).serialize(), (invite) ->
alert(invite.status)
if invite.status
$('#sending_invite').hide()
$('#invite_sent').show()
$('#invite_email').val('')
else
alert('start')
$('#sending_invite').hide()
$('#invite_fail').show()
alert('end')
I put these alerts there, and all of them are shown before page refreshes. I've tried returning false instead of preventingDefault, and is also didn't work. Can anyone see what I am missing?
Just found out what was happening. When rails generated the form, it made it with the same name of another form I had for a similar purpose, and I've already had a js function to deal with the other one. All I had to do was change de id of this one, and everything works now.
I have a form that when is submited it posts to a div. Ok, so I found the issue that i was getting double submissions, so i tried to apply some jquery plugins i found, but they were useless because if you double clicked fast enough I still got a double submission. From those I found i saw the best way to prevent it was with
if (this.beenSubmitted) return false;
else
this.beenSubmitted = true;
but then, I noticed that if the form needed to be sent again, the user would have to refresh the page in order to send it. In my case, I want them to be able to send again after is sent, (Im not contradicting myself, because it would be diferent content). To explain it better, this form post ideas. If you want to post 2 diferent ideas you would have to refresht he page to post. Preventing double submission would help from submitting the same idea twice if you clicked fast enough. So, what I did is that I added this "5000":
if (this.beenSubmitted) return false, 5000;
else
this.beenSubmitted = true;
So, now it refreshed my page. But im a little picky, lol. So I find it annoying that the whole page has to refresh. What if your typing and then it refreshes. I can always lower the 5000 I know, but I still find it annoying in case you start to browse the website or to zoom in, you end up refreshed.
So, my question is, is there any way to just refresh the form? or a better way to prevent double submission that actually works for this case (that ur able to submit after a few secs) ?
this is script:
<script type="text/javascript">
$(document).ready(function(){
$("form#myform").submit(function() {
var addcontent = jQuery('#addcontent').attr('value');
if ( addcontent.replace(/\s/g,"") == "" ) return false;
if (this.beenSubmitted) return false,5000;
else
this.beenSubmitted = true;
$.ajax({
type: "POST",
url: "post.php",
data:"addcontent="+ addcontent,
success: function(){blah blah blah, ton sof code here including pagintion here, insert into a div here also, if u need this let me know.
});
</script>
Most of that I did it from asking questinos here. My Jquery and Ajax knowledge isnt the best one.
THanks for the help =}
Rate limiting to prevent malicious behavior in ExpressJS
The above link has something about putting a timer on the submit button so that you can't click it again within 3 seconds.
<script>
var submitTimer = new Collate(3000);
</script>
<form action="post" onsubmit="return submitTimer.idle();">
why don't u use the this.beenSubmitted = true approach and combine it with a timeout? for example after 5000ms u execute the timeout and set this.beenSubmitted to false.
The statement:
return false, 5000;
will always return 5000, the use of false is redundant and pointless.
To reset a form without reloading the page (which won't necessarily reset the form in some browsers), use a reset button or call the form's reset method. You can use an onreset listener to update the beenSubmitted property if the form is reset.
Multiple submission of a form has been an issue since forms were invented, it's usually dealt with at the server (if two identical requests are received, ignore the second).
Using script at the client is unreliable since you don't know what the server is doing and you have to guess whether or not the form needs to be resubmitted.
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.
I want to have a feature to submit several forms on a page when the user leaves the page. There is this "do you wanna save?" question and my code so far is like this:
function checkForChanges( ) {
if (window.formform1Changed == true) {
if (window.asked == false) {
window.asked=true;
doSave = confirm("Wanna save? Click OK")
}
if (window.doSaveForms || doSave) {
window.doSaveForms = true;
document.forms.form1.submit();
}
}
if (window.formform2Changed == true) {
if (window.asked == false) {
window.asked=true;
doSave = confirm("Wanna save? Click OK.")
}
if (window.doSaveForms || doSave) {
window.doSaveForms = true;
document.forms.form2.submit();
}
}
}
It may seem a little bit of overkill but it is generated automatically by our template engine and may be extended to more forms.
The body tag:
<body
onLoad="init();
window.formform1Changed=false;
window.asked=false;
window.doSaveForms=false;
window.formform2Changed=false;"
onbeforeunload="checkForChanges();">
And interesting part of one of the forms (the other one looks identically:
<input value="xyz" id="la" onchange="window.formform1Changed=true;" />
<input name="save" onclick="window.formform2Changed=false; window.formform1Changed=false;" type="submit" value="save" />
Now to the problem:
If I change values in both forms and navigate away from the page, the question from the first form pops up. I click OK, the form is saved but the form1.submit() triggers a new onBeforeUnload event which breaks the whole logic of my idea.
The question now would be if there is a way to submit all forms on a page when only asking one time when the user navigates away?
Any help is highly appreciated!
Thanks.
Form submissions requires post-back, once you submit the first form, your page is redirected to the "action" of that form and you will lose the information in the rest of the forms you have.
Having multiple forms on the page is not the best idea, however, if you absolutely have to have them, the way to save all of them would be to replace full post-back with an AJAX call to a web-service (or a stand-alone page, that accepts query string parameters, though it's not as secure or flexible way). That way you can submit each form over the AJAX call without page redirecting.
As SLaks said, you will not be able to submit multiple forms in the way you are trying. You do have some other options though. Instead of traditional form submits you could make some kind of ajax calls to save the form data you care about. Here is an example using jquery and php (link)