Use fancybox to allow/prevent form submission - asp.net-mvc-3

Below is the jQuery I'm using to try and prevent/allow a form to be submitted once the user clicks the submit button. The idea will be to present a fancybox modal dialog window with the data the user entered for review. If they ,like, they click Looks Good! and the form is submitted back to the ASP MVC3 controller. If not, since the e.preventDefault method has already been called the modal window closes and they can re-enter the data.
The problem is, obviously as I have this written now, if the user is happy with the data they've entered, the whole thing will go into an infinite loop since I'm the Look's Good! button calls the method that displayed it in the first place.
Is there a way to create a "standalone" method inside the submit() function so I would have access to the event object and, if not, what would be a better way (i.e. actually works) to allow the form to submit after clicking the Look's Good! button?
//Form submit functions
$('form').submit(function (e) {
e.preventDefault();
if ($('#AccountNumber').val() != $('#doubleaccount').val()) {
alert("Please re-enter the correct account number!");
} else {
var display = "<h1>Test</h1>" +
"<input type='button' value='Looks Good!' onclick='submit()'/>" +
"<input type='button' value='Try Again...' onclick='cancel()'/>";
$.fancybox(display, {
// fancybox API options
fitToView: false,
autoScale: true,
autoDimension: true,
closeClick: true,
openEffect: 'fade',
closeEffect: 'fade',
closeBtn: true,
openSpeed: 'fast',
closeSpeed: 'fast'
});
}
});
});//End doc.ready()
function submit() {
$('form').submit();
}
function cancel() {
$.fancybox.close();
}

Since you are preventing default, then you may need to submit the form via ajax to avoid the loop. I think this would do the trick :
function submitForm(){
jQuery.ajax({
cache: false,
type: "POST",
url: "process.asp", // your controller
data: jQuery("#myForm").serialize(), // serialize form with id="myForm"
success: function(data){
jQuery.fancybox("form successfully submitted"); // confirmation message
jQuery('#myForm')[0].reset(); // clear form fields
}
});
}
jQuery(function($) {
$("#myForm").on("submit", function(e){
e.preventDefault();
if ($('#AccountNumber').val() != $('#doubleaccount').val()) {
// validation : something went wrong
alert("Please re-enter the correct account number!");
} else {
var display = "<h1>Test</h1>" +
"<input id='submit' type='button' value='Looks Good!'/>" +
"<input id='cancel' type='button' value='Try Again...'/>";
$.fancybox(display,{
// other API options
afterShow: function(){
$("#submit, #cancel").on("click", function(event){
if( $(event.target).is("#submit") ){
submitForm();
}
$.fancybox.close();
});
}
}); // fancybox
}
}); // on submit
}); // ready
Notice that I added IDs to the form as well as the buttons to submit or cancel so I can bind events to all those selectors. Also notice that I used the afterShow callback to bind the click events in my buttons inside fancybox.
Useful to read : Ajax serialize docs
NOTE : .on() requires jQuery v1.7+
EDIT : you could actually replace this line in your validation conditional
alert("Please re-enter the correct account number!");
by this one :
$.fancybox("Please re-enter the correct account number!");
so everything will look more consistent ;)

Related

ajax form submission - skip url processing and go directly to success function?

Haven't come across this before with ajax. On click of a button I am posting a form with ajax. In the successful return function I am opening up a modal window in bootstrap 3 with a single parameter attached from the previous form submission.
I am using the modal as a confirmation window to confirm a user deletion. I am using ajax again then in the modal to do the actual deletion of the user in the db and returning success or fail.
Since all the operations are being processed in the actual modal's ajax (confirm the username exists then perform the delete operations)... is there a way I can skip the initial form processing? In this example p_delete_user.php' really does absolutely nothing other than allow me to return and attach the username parameter to the modal I open.
Can I skip this step somehow and go straight to my success calls with the attached parameter value. I have no need to check if the param is valid or not in this step as the validation occurs in the ajax of the modal that is opened.
my ajax:
// delete user account
var deleteAccount = function() {
$('#delete-user').on('click', function () {
var $form = $(this).closest('form');
$.ajax({
type: 'post',
url: '/spc_admin/process/p_delete_user.php',
data: $form.serialize(),
dataType : 'json'
}).done(function (response) {
if (response.success) {
// user account exists so show confirmation modal
$('#modal-ajax').load('/spc_admin/modals/m_delete_user.php?username='+response.username+'');
$('#modal-ajax').modal('show');
}
else
{
// show error toast
toastr.error('An error has occurred. Please contact support.', 'Error');
}
});
});
}
Use Javascript to get the username from the form, and put that directly into the modal:
var deleteAccount = function() {
$('#delete-user').on('click', function () {
var username = $(this).closest('form').find("input[name=username]").val();
$('#modal-ajax').load('/spc_admin/modals/m_delete_user.php?username='+encodeURIComponent(username));
$('#modal-ajax').modal('show');
});
}

Validate (Bassistance) before sending to fancybox

I'm using the bassistance validation plugin and have a small script that catches the second submit-button (called preview) and sends the data via ajax to fancybox. I'ld like to validate the forms before they are send to fancybox. At the moment they're only validatet, if I send the forms via the submit-button. I tried in various ways (e.g. I put the call for validation directly after the if and so on) but couldn't get it work. Maybe there's a way to let validate know that it should also react, when the preview-button is hit?
My Code:
$(function() {
$('#myform *').tooltip();
$('#myform ').validate();
});
$(document).ready(function(){
$(':submit').click(function(){
for (var i in CKEDITOR.instances){
CKEDITOR.instances[i].updateElement();
}
var value = $(this).attr("id");
if (value == 'preview') {
$.fancybox.showLoading();
$.ajax({
type : "POST",
cache : false,
url : "../mypath/",
data : $('#myform').serializeArray(),
success : function(data) {
$.fancybox(data, {
'minWidth': '100%',
'minHeight': '100%',
});
}
});
return false;
}
});
});
If i'm not wrong, the Bassistance Validator plugin relies on the fact that if you SUBMIT a form, and the requirements are not met, the function returns a "false" on that submit, enabling you to visually see the errors made.
In your source code, you correctly initialized the Bassistance validator plugin at the very beginning of your code ( I assume you created the rules for it directly on the input fields for example minlength="2" required ) but there is a problem: there is no hook for the SUBMIT event of the submit button, but only for the CLICK event on that button.
There is a simple example on the Bassistance website that shows how you can use custom submit events for the plugin:
http://jquery.bassistance.de/validate/demo/ajaxSubmit-intergration-demo.html
Basically, what you need to do is to insert the intelligent part of your code into
jQuery("#yourform").validate({
submitHandler: function(form) {
jQuery(form).ajaxSubmit({
/*
Here you can do the following:
1) Update the instances of CKEDITOR
2) Check if the submit is in the preview mode
3) If yes
- do your fancy stuff
- return false so that the real submit is not triggered
If not
- return true so that the real submit handler is evaluated by the browser and the POST is triggered
*/
});
}
});

Jquery Mobile submit button not working after page refresh

I have a single page mark-up with popup divs that contain forms that the user can use to update his/her account information. After form submission the popup closes and the page refreshes showing the updated information that is located within a li (this seems to be working). The problem is, if the user goes back and tries to update again the button within the popup is not submitting.
Thanks in advance for any suggestions!!!
Javascript
$('#updateadmin').click(function() {
var admin = $('#adminform').serializeArray();
/*alert(admin);*/
$.ajax({
type: "POST",
url: 'adminupdate.php',
data: admin,
success: function(data) {
if(data=="success") {
$('#admindiv').popup('close');
$.mobile.changePage('companyinfo.php', {
allowSamePageTransition: true,
transition: 'none',
reloadPage: true,
changeHash: false
});
} else {
$('#adminupdatestatus').html(data).css({color: "red"}).fadeIn(1000);
}
}
});
return false;
});
It sounds like the #updateadmin link/button is located on the page that gets reloaded, if this is the case then you should delegate your event handler so it affects matching elements in the DOM for all time, not just when the code runs.
You would change this:
$('#updateadmin').click(function() {
to this:
$(document).on("click", "#updateadmin", function() {
This works because you're now attaching the event handler to the document element which always exists. When events reach the document element they are checked to see if the element on which they originally fired matches the selector we put as the second argument for .on().
Documentation for .on(): http://api.jquery.com/on

Jquery load in Dialog is repeated exponentially

I have a really annoying issue with jQuery and/or the jQuery UI Dialog Box.
After clicking on a special link a modal dialog will pop up with some loaded content (ajax) and inside this loaded content are new links/buttons that load their url inside the same div Box, so the dialog still is loaded, but with new content then. The Problem is, that if you link on that link (inside a fresh loaded dialog box and on a recently reloaded website) it works as it should, but with the second click it loads the url twice, with the third it loads 4 times ... It growing exponentially with every new link loaded inside the dialog. I testet this with a counter stored inside $_SESSION.
This is the Javascript Code:
var somedialog = $('<div></div>').dialog({
autoOpen: false,
resizable: false,
modal: true,
/*show: 'fade',
hide: 'puff',*/
closeOnEscape: true,
close: function(){
}
});
function openInDialog(url, title, width, height)
{
somedialog.empty();
somedialog.dialog("option", "width", width);
somedialog.dialog("option", "height", height);
somedialog.dialog("option", "title", title);
somedialog.load(url,{},function (responseText, textStatus, XMLHttpRequest)
{
somedialog.dialog('open');
}
);
//somedialog.load(url,{},function (responseText, textStatus, XMLHttpRequest){
// dialogdiv.somedialog('open');
//});
}
$('a.ajaxBuyItemDialog').on('click',function(){
openInDialog(this.href, this.title, 400, 300);
//prevent the browser to follow the link
return false;
});
There seemed to bee other people with this issue, but that was not a very effective discussion: https://stackoverflow.com/questions/6471360/jquery-load-after-load-repeated-results-problem
Thanks for your help!
EDIT:
This is part of the code which is located in the loaded script:
$("#_BUYITEM_FORM").live('submit', function(){
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // the file to call
success: function(response){ // on success..
$("#_BUYITEM_CONTENT").html('<p class="AjaxLoaderImg"><span>Einen Moment bitte...</span></p>');
$("#_BUYITEM_CONTENT").html(response); // update the DIV
}
});
return false; // cancel original event to prevent form submitting
});
Without it I can't get it to refresh the dialog box with new content.
It seems that your javascript code is replicated in every $('a.ajaxBuyItemDialog') destination page clicked. Adding that script to the dialog again at every click causes event to be triggered more than once.
If you reload the script numerous times it will add a new submit handler to form each time since you are using live().
live() will delegate the handler to the document and thus should either only be called once or you need to call die() before script loads each time.
if you were to get rid of using live() you could move the submit handler to the success callback of load() and use submit() rather than live(). If the original form is replaced...the original submit() event handler will also be gone
"Dirty" solution
function watchBuyItemForm(){
$("#_BUYITEM_FORM").submit(function(){
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // the file to call
success: function(response){ // on success..
somedialog.html(ajaxLoader);
somedialog.html(response); // update the DIV
watchBuyItemForm();
}
});
return false; // cancel original event to prevent form submitting
});
}

ASP.NET MVC - How to prevent double click submit with jquery.validate.unobtrusive lib?

I need to avoid the double click submitting behavior. I'm using the client validation with the unobtrusive library. I have the following code for avoiding the double clic:
jQuery.fn.preventDoubleSubmit = function () {
var alreadySubmitted = false;
return jQuery(this).submit(function () {
if (alreadySubmitted)
return false;
else {
alreadySubmitted = true;
}
});
};
jQuery('form').preventDoubleSubmit();
Unfortunately, if my form has some validable fields (for example, a required field), the code above is still being fired, hence, even if I correct any mistakes on the form, I won't be able to submit it again.
How can I fire the double click code after the validation has been succesfully done?
You can also use the JQuery One event.
I have found that I could get past most guards against double-clicks by double-clicking fast. Using the one event is the only true way to make sure the event is only fired once. I don't think this technique will work "out of the box" with an input type=submit tag. Instead, you can simply use an input type=button or JQueryUI's .button().
$("#submitButton").one("click", function(event) {
$('#theForm').submit();
});
If you need to re-wire the event on a validation error (or other circumstance), I recommend that you create a function for the event handler. The function isn't necessary in this example because all the event handler does is submit the form, but in more complicated scenarios you may want to avoid repeating yourself.
function submitClick(event) {
$('#theForm').submit();
}
$("#submitButton").one('click', function(event) {
submitClick(event);
});
// This handler will re-wire the event when the form is invalid.
$('#theForm').submit(function(event) {
if (!$(this).valid()) {
event.preventDefault();
$('#submitButton').one('click', function(event) { submitClick(event); });
}
});
You could obviously add the disabling code here if you wanted to give feedback to the user that the button doesn't work anymore. One great side-effect of using the One event is that you don't actually have to make the button disabled, you can use a style of your own.
function submitClick(event) {
$('#submitButton').addClass('disabledButton');
$('#theForm').submit();
}
$("#submitButton").one('click', function(event) {
submitClick(event);
});
// This handler will re-wire the event when the form is invalid.
$('#theForm').submit(function(event) {
if (!$(this).valid()) {
event.preventDefault();
$('#submitButton').one('click', function(event) { submitClick(event); });
$('#submitButton').removeClass('disabledButton');
}
});
JQuery One Event: http://api.jquery.com/one/
I solved it with the following code:
var tryNumber = 0;
jQuery('input[type=submit]').click(function (event) {
var self = $(this);
if (self.closest('form').valid()) {
if (tryNumber > 0) {
tryNumber++;
alert('Your form has been already submited. wait please');
return false;
}
else {
tryNumber++;
}
};
});
NOTE: You can also replace the:
return false;
line, for:
self.attr('disabled', true);
BUT, if you use the name of your submit buttons on your controller for extra logic, they will be sent as null. (you can use an additional hidden field to charge them before submitting)
that's it, hope it helps
Rodrigo
EDIT: Thanks to these posts:
jquery newbie: combine validate with hidding submit button
Why not just use:
function disableButtons() {
var form = $(this);
var btns = $("input:submit", form);
if (!form.valid()) {
// allow user to correct validation errors and re-submit
btns.removeAttr("disabled");
} else {
btns.attr("disabled", "disabled");
}
}
to disable your buttons and activate it using:
$("form").bind("submit", disableButtons);
Based on Ryan P's popular answer I created the following generic solution that also works with my ajax form.
decorate your custom submit button with the following class:
<button type="button" class="one-click-submit-button">Submit</button>
Add the following to your javascript file:
function OneClickSubmitButton() {
$('.one-click-submit-button').each(function () {
var $theButton = $(this);
var $theForm = $theButton.closest('form');
//hide the button and submit the form
function tieButtonToForm() {
$theButton.one('click', function () {
$theButton.hide();
$theForm.submit();
});
}
tieButtonToForm();
// This handler will re-wire the event when the form is invalid.
$theForm.submit(function (event) {
if (!$(this).valid()) {
$theButton.show();
event.preventDefault();
tieButtonToForm();
}
});
});
}
OneClickSubmitButton();
since this is an ajax form we want to reload the handlers if we fail server validation.
function MyForm_OnSuccess() {
if (true if your form passed validation logic) {
//do something since your form submitted successfully
} else { //validation failed on server
OneClickSubmitButton(); //reinitialize the button logic
}
}
Obviously if you don't have ajax forms you can omit the whole OneClickSubmitButton function business and run $('.one-click-submit-button').each(... directly.
I have a form that uses MVC3 unobtrusive validation, and a viewmodel with a [RemoteAttribute].
It looks to me like the form's submit event only fires after all validation has passed. I'm currently using this, and it seems to work:
<input type="submit" value="Submit the Form"
data-app-disable-on-submit="true" />
$('form').live('submit', function() {
$(this).find('input[type="submit"][data-app-disable-on-submit="true"]')
.attr('disabled', 'disabled');
})
;
I set breakpoints on both the remote attribute validation action method and the HttpPost action method. Clicking the submit button the first time hits the breakpoint on the validation action method. At this point, the button is still enabled. I can click it multiple times, and after resuming the validation method, the HttpPost is hit only once. When the HttpPost is hit, the submit button is disabled.
Update
Right you are Alex. So an updated version of the above would look like this:
$('form').on('submit', function() {
$(this).find('input[type="submit"][data-app-disable-on-submit="true"]')
.attr('disabled', 'disabled');
})
$('form').submit(function () {
$('input[type="submit"]', this).attr('disabled', 'disabled');
});
I use a different approach to this. Not wiring to the click event of the button, but to the submit event of the form. Works like a charm to prevent multiple simultaneous submits of forms.
function initFormsToPreventSimultaneousSubmits(selector) {
if (!selector) {
selector = 'form'; // No selector supplied, apply to all forms on the page
}
// Make sure all forms that conform to selector are marked as not submitting
$(selector).each(function()
{
var $form = $(this);
$form.data('submitting', false);
});
// Attach to submit event of all forms that conform to selector
$(selector).off('submit').on('submit', function (e) {
var $form = $(this);
if (!$form.valid || $form.valid()) { // Make sure to only process when the form is valid or jquery validation is not used
if ($form.data('submitting')) {
// form is already submitting. Classic case of double click on one of the submit buttons of the form. Stop the submit
e.preventDefault();
return false;
} else {
// All ok, mark the form as submitting and let the form perform the submit
$form.data('submitting', true);
return true;
}
}
});
}
On document ready i call initFormsToPreventSimultaneousSubmits() to init all forms on the page.
Only thing to remember is that when u use a ajax form post is to call the initFormsToPreventSimultaneousSubmits('#formId') on the OnComplete event of the AjaxOptions settings. Because otherwise the form will still be marked as submitting when its done. When a 'normal' form post is used this is not an issue.
Extends answers by Alex and Ryan P to accounts for situations where jQuery Validation might be missing and where multiple submit buttons exist in a single form.
oneClickSubmitButton = function () {
$('input[type=submit], button[type=submit], input[type=image]').each(function () {
var $theButton = $(this);
var $theForm = $theButton.closest('form');
//hide the button and submit the form
function tieButtonToForm() {
$theButton.one('click', function () {
$theButton.addClass('ui-state-disabled');
});
}
tieButtonToForm();
$theForm.submit(function (event) {
// Only proceed for the clicked button
if (!$theButton.hasClass("ui-state-disabled"))
return;
// If jQuery Validation is not present or the form is valid, the form is valid
if (!$theForm.valid || $theForm.valid())
return;
// Re-wire the event
$theButton.removeClass('ui-state-disabled');
event.preventDefault();
tieButtonToForm();
});
});
};
I was able to fix a similar issue with a couple of lines of code. I prefer this if you don't want to "alert" to user that they double clicked and just silently ignore the second click.
I just made a global javascript variable that I toggled when my function was executing during a critical section. This kept subsequent function calls from re-executing the same section.
var criticalSection = false;
SomeOnClickEventFired = function () {
if (!criticalSection)
{
criticalSection = true;
//Ajax Time
criticalSection = false;
}
}

Resources