jQuery dialog won't stop re-opening - ajax

Problem with field validation and two jQueryUI dialogs.
There is a registration form in the first jQUI dialog.
Field validation on the username field using AJAX. If field fails validation (already exists), PHP file returns a number > zero and an error message is displayed in a second jQueryUI dialog.
However, when user closes 2nd dialog, it immediately re-opens, forever.
Any thoughts?
$("#c_username").blur(function() {
var uu = ($(this).val()).toLowerCase();
$(this).val(uu); //in case user did not input as all lowercase
$.ajax({
type:'POST',
url: 'ajax/ax_all_ajax_fns.php',
data:'request=does_username_already_exist&username=' + uu,
success: function(data) {
if (data != 0) {
$('#alert').html('Username <span style="font-weight:bold;color:darkgreen;">' +uu+ '</span> already exists. Please enter another.');
$('#alert').dialog({
title: 'Username already exists:',
width: 400,
close: function() {
$(this).dialog('destroy');
}
});
$("#c_username").addClass('field_invalid').focus();
}else{
alert("Username is okay");
}
}
});
});

$("#c_username").addClass('field_invalid').focus(); focuses the input behind the dialog. When you click the close button on the dialog, the input's blur event is raised again, causing another ajax call, and another dialog to be opened.
Try moving the focus() call to the close callback on the dialog. You could also try displaying the message in a span next to the input instead of in a dialog so focus issues can't happen.

Related

magento hide validation message

On my magento site, validation is done by prototype validation. Everytime validation fails, error message for that field appears. As soon as you start typing in that field the error message fades out. What I want to do is fade out the error message if user clicks anywhere in the form. link to the javascript file
https://github.com/atetlaw/Really-Easy-Field-Validation/blob/master/validation.js
In the following snippet remember to replace FORM_ID with the ID of your form.
Event.on('FORM_ID', 'click', function() {
// fall back to plain hiding if cannot fade
var hide = self.Effect && Effect.Fade || Element.hide;
// this = form being watched
this.select('.validation-advice').each(hide);
});

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');
});
}

Use fancybox to allow/prevent form submission

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 ;)

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

Resources