I have a form for both creation and editing some fields.I am using Ajax validation for that before submitting the form like
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'candidates-profiles-form',
'enableAjaxValidation'=>true,
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
'validateOnChange'=>false,
'beforeValidate'=>"js:function(form) {
if((form.data('submitObject')[0].id ) == 'cancel'){
alert('cancalclicked');
this.validateOnSubmit = false;
this.validateOnChange = false;
this.beforeValidate = ''; // the problem is caused by this line
form.submit();
return false;
}
else{
alert('submitclicked');
return true;
}
}",
'afterValidate'=>"js:function(form, data, hasError) {
if(hasError) {
alert('We have detected some input errors and has not saved your data. Please click Ok to correct them.');
return false;
}
else {
if(confirm('We have validated your input and we are ready to save your data. Please click Ok to save or Cancel to return to input.'))
return true;
else
return false;
}
}",)
)); ?>
After creation it is perfectly coming in afterValidate function and works fine.But after editing it is not all coming in afterValidate. But it is coming in beforeValidate and submitting the form with out reaching afterValidate .
Make sure you have $this->performAjaxValidation($model); in your controller for that action.
Related
i have a simple form: when i submit it without javascript/jquery, it works fine, i have only one insertion in my data base, everything works fine.
I wrote some jquery to have result in ajax above the input button, red message if there was an error, green if the insertion was done successfully. I also display a small gif loader.
I don't understand why when i use this jquery, two loaders appear at the same time and two insertions are done in my database.
I reapeat that when i comment the javascript, it works fine, i'm totally sure that my php is ok.
$('#addCtg').submit(function () {
var action = $(this).attr('action');
var name = $('#name').val() ;
$('.messages').slideUp('800', function() {
$('#addCtg input[type="submit"]').hide().after('<img src="spin.gif" class="loader">');
$.post(action, {
name: name
}, function (data) {
$('.messages').html(data);
$('.messages').slideDown('slow');
$('.loader').fadeOut();
$('#addCtg input[type="submit"]').fadeIn();
});
});
return false;
});
I really don't understand why it doesn't work, because i use the 'return false' to change the basic behaviour of the submit button
Basic php just in case:
<?php
require_once('Category.class.php');
if (isset($_POST['name'])) {
$name = $_POST['name'] ;
if ($name == "") {
echo '<div class="error">You have to find a name for your category !</div>' ;
exit();
} else {
Category::addCategory($name) ;
echo '<div class="succes">Succes :) !</div>' ;
exit();
}
} else {
echo '<div class="error">An error has occur: name not set !</div>';
exit();
}
And finnaly my function in php to add in the database, basic stuff
public static function addCategory($name) {
$request = myPDO::getInstance()->prepare(<<<SQL
INSERT INTO category (idCtg, name)
VALUES (NULL, :name)
SQL
);
$r = $request->execute(array(':name' => $name));
if ($r) {
return true ;
} else {
return false ;
}
}
I rarely ask for help, but this time i'm really stuck, Thank you in advance
You're calling: $('.messages') - I bet you have 2 elements with the class messages. Then they will both post to your server.
One possible reason could be because you are using button or submit to post ajax request.
Try this,
$('#addCtg').submit(function (e) {
e.preventDefault();
var action = $(this).attr('action');
var name = $('#name').val() ;
$('.messages').slideUp('800', function() {
$('#addCtg input[type="submit"]').hide().after('<img src="spin.gif" class="loader">');
$.post(action, {
name: name
}, function (data) {
$('.messages').html(data);
$('.messages').slideDown('slow');
$('.loader').fadeOut();
$('#addCtg input[type="submit"]').fadeIn();
});
});
return false;
});
In my form, I have given a confirmation message before saving.
CHtml::submitButton('Save', array('confirm'=>'Are you sure you want to save?'));
But the message box appears two times... What is wrong ?
Here is the form where you can got the answer of your thing... this is one way of doing it...!!!
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'customer-form-guest',
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
'afterValidate' => 'js:function(form, data, hasError) {
if(hasError) {
alert("There are errors in form inputs please resolve it.");
}
else
{
var r = confirm("Are you sure y7ou want to do this ..?");
if(r == true)
{
return true;
}
else
{
return false;
}
}
}' ),
'htmlOptions'=>array('role'=>"form")));
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save',
array('confirm'=> 'Are you sure?')); ?>
When Click on Save then Same Page render than Controller generate view that time also who messege that's an issue. You have to pass some value in URL and then When view load that time just write condition for that does't show twice.
I am working on a jQuery validation "plugin" (not yet a plugin) that use my Zend_Form validators to verify the fields before submitting, client-side, so I only have to specify my constraints one time instead of two (Zend Validators + jQuery Validate Plugin, for example).
I store the validation AJAX requests for each field, then wait for them to finish, and then read the results and show or not an error message.
The problem : when I enter validated strings and hit submit, it shows no errors (good so far), but I have to re-click the submit button the form to really submit it.
Making a return true or false inside the .whenAll function is ignored and does not work, that's why I used a flag to tell the function if yes or no it can really submit the form.
$(function() {
var form = $('form'); // target form
var requests = [], validations = []; // used to store async requests and their results
var nbInputs = $('input[type="text"], input[type="password"]').length; // number of inputs we want to check in the form
var cancelSubmit = true; // skip validation flag
form.submit(function( ) {
// if we call the submit inside the function, skip validation and do submit the form
if(cancelSubmit === false) {
console.log('[-] cancelSubmit is false. Validation skipped.');
this.submit();
return true;
}
console.log('[-] Entering validation');
// resetting requests and validations
requests.length = 0;
validations.length = 0;
// for each input (text/password), storing the validation request
$('input[type="text"], input[type="password"]').each(function(i) {
var validatorField = $(this).attr('data-validator');
var valueField = $(this).val();
postData = {
validator: validatorField,
value: valueField
};
// storing requests into an array
requests.push($.post('/validate', postData));
});
(function($) {
$.whenAll = function() {
return $.when.apply($, arguments);
};
})(jQuery);
// when all the requests are done and returned a response
$.whenAll(requests).then(function() {
// show the validation status for each input
$.each(requests, function(i, element) {
element.done(function(data) {
// response is formatted like this
// { valid: 1 } or { valid: 0, message:"This is the error message" }
json = $.parseJSON(data);
formGroup = $('input:eq('+i+')').parent();
// if it isn't valid, show error and store result
if(json.valid == 0) {
if($('span.help-block', formGroup).length == 0) {
$(formGroup).addClass('has-error').append('<span class="help-block">'+json.message+'</span>');
$('label', formGroup).addClass('control-label');
}
validations.push(0);
}
// else, remove error (if there was) and store the result
else if(json.valid == 1) {
if($(formGroup).hasClass('has-error'))
{
$(formGroup).removeClass('has-error');
$('.help-block', formGroup).remove();
}
validations.push(1);
}
// if we got all the validations required
if(validations.length == nbInputs)
{
console.log('[-] All validations have been done.');
// and if no error ("0") in the results, we resubmit the form with skip-flag
if($.inArray(0, validations) == -1){
console.log('[-] No errors. Submitting form.');
cancelSubmit = false;
form.off('submit');
form.submit();
}
else
console.log('[-] There is still errors.');
}
});
});
});
// there are errors, so we won't submit the form
if(cancelSubmit === true)
return false;
});
});
Do you see a logic flaw in my code ? Maybe re-submitting the form with a flag isn't the right way to do it ?
You're returning from a sub scope rather than from the form submit handler. Instead, always prevent the submit, and then force it to submit with form[0].submit() when you want it to submit.
form.submit(function(e) {
e.preventDefault();
...
// now i want to submit...
form[0].submit();
form[0].submit() will bypass your jquery bound submit handler.
What I am trying to accomplish is a (very simple) email validation using jQuery, but no matter what I do, the form will just keep submitting.
<form id="rfq" name="rfq" action="rfq_form" method="post" enctype="multipart/form-data">
...
<input type="image" id="submit" name="submit" src="submit.png" border="0" />
JS email validation:
//$("#rfq").submit(function() { doesnt seem to work either
$('#submit').click(function() {
var email = $('#email').val();
if(email.indexOf("#") == -1){
$("#email").addClass('invalid');
return false; // cancel form submission if email invalid
}
return false; // return true if no errors once i get it working
});
Working Example
First, make sure all event handlers are attached once the DOM is "ready"
I'm using .submit() on the actual form.
$(document).ready(function() {
// now that document is "ready"
$('#formId').submit(function() {
var email = $('#emailInput').val();
alert(email);
if(email.indexOf("#") == -1){
alert("invalid!");
return false; // cancel form submission if email invalid
}
alert("valid!");
return true; // return true if no errors once i get it working
});
});
Try wrapping your code in a ready block.
$(document).ready(function(){
// your code here
});
You should also be using the submit event on the <form> element, I think.
This is going to work. If you don't understand why, feel free to ask :)
var validated = false;
$(document).ready(function(){
$("#rfq").submit(function(event) {
if (validated === true) {
return true;
}
event.preventDefault(); // prevent submission
var email = $('#email').val();
if(email.indexOf("#") == -1){
$("#email").addClass('invalid');
return;
}
validated = true;
return $(this).trigger('submit');
});
});
You could try using this function to validate your address.
function validateEmail(elementValue){
var emailPattern = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
return emailPattern.test(elementValue);
}
And then modify your code to submit the form.
$('#submit').click(function() {
var email = $('#email').val();
if(!validateEmail(email)){
$("#email").addClass('invalid');
}
else {
$("form").submit();
}
});
I have a JavaScript method that i want to validate a form
if the validation fails so
if (validationChecks ...... ){
return alert("message")
}
else{
//proceed
}
however no matter what i do in the if the form still seems to submit, any ideas?
you should return false after checking validation.
if (validationChecks ...... ){
alert("message")
return false; }
else{
//procced
}
You have spelt 'return' wrong. Also, returning an alert will not work, you'll need to return false explicitly to stop the form submitting.
if (validationChecks ...... ){
alert("message");
return false;
}
else{
//procced
}
Your validation must return false when the form is not valid, and if you're calling your validationin onSubmit, then you must make sure that you include a return statement there as well:
<form onSubmit="return validationChecks();">
You need to return false; in the case of failure