I'm trying to submit form using j-query, before submitting it should do some validation and in that I've validation for capcha using ajax. Everything works fine without ajax validation.
<form id="RegistrationForm" name="RegistrationForm" method="post" action="save.php" >
jquery code
$('#RegistrationForm').submit(function(){
//some validation goes here
if($('#captcha').val() != '')
{
var captcha = $('#captcha').val();
$.ajax({
url:'validate.php',
type:'POST',
data:{captcha:captcha},
success: function(data){
if(data == 'false')
{
alert('Wrong Captcha is typed!');
return false;
}
else
{
alert('enter');
document.getElementById("RegistrationForm").submit();
return true;
}
}
});
}
});`
while submitting form it shows alert "enter" but form not getting submitted.
Thanks in advance.
You probably need to change your variable to a JSON seening how you are retreiving from a php. if thats not the solution try
if (data){
}else{
}
FYI this is not jquery validation. Jquery validation is a library set up in order to make sure the proper fields are set up correctly before submitting. What you have done is tested if the captcha is correct after submitting.
try something like this
$(function(){
$('#RegistrationForm').submit(function(){
if($('#captcha').val() != ''){
var captcha = $('#captcha').val();
$.ajax({
url:'validate.php',
type:'POST',
async:false,
data:{captcha:captcha},
success: function(response){
if(response == 'false')
{
alert('Wrong Captcha is typed!');
return false;
}
else
{
alert('enter');
return true;
}
}
});
}
});`
})
Try making ajax synchronous
$.ajax({
url:'validate.php',
type:'POST',
async: false,
data:{captcha:captcha},
success: function(data){
if(data == 'false')
{
alert('Wrong Captcha is typed!');
return false;
}
else
{
alert('enter');
document.getElementById("RegistrationForm").submit();
return true;
}
}
});
I think the problem is when the ajax request returns other value than false , every time you are again calling from submit , i think every time it calls to submit function , but could not submit successfully . because it calls submit function recursively.
try
$('#RegistrationForm').submit(function(){
//some validation goes here
if($('#captcha').val() != '')
{
var captcha = $('#captcha').val();
$.ajax({
url:'validate.php',
type:'POST',
data:{captcha:captcha},
success: function(data){
if(data == 'false')
{
alert('Wrong Captcha is typed!');
return false;
}
else
{
alert('enter');
}
}
});
}
});
Related
I want to prevent multiple ajax calls (user holds enter key down or multi presses submit or other)
I'm thinking, the best way is to use a var with the previous form post values and compare them at each click/submit.. Is it the same? : Then do nothing
But I don't know how to go about it
Here is my javascript/jquery:
$('form').submit(function() {
$theform = $(this);
$.ajax({
url: 'validate.php',
type: 'POST',
cache: false,
timeout: 5000,
data: $theform.serialize(),
success: function(data) {
if (data=='' || !data || data=='-' || data=='ok') {
// something went wrong (ajax/response) or everything is ok, submit and continue to php validation
$('input[type=submit]',$theform).attr('disabled', 'disabled');
$theform.unbind('submit').submit();
} else {
// ajax/response is ok, but user input did not validate, so don't submit
console.log('test');
$('#jserrors').html('<p class="error">' + data + '</p>');
}
},
error: function(e) {
// something went wrong (ajax), submit and continue to php validation
$('input[type=submit]',$theform).attr('disabled', 'disabled');
$theform.unbind('submit').submit();
}
});
return false;
});
Not very creative with naming vars here:
var serial_token = '';
$('form').submit(function() {
$theform = $(this);
if ($(this).serialize() === serial_token) {
console.log('multiple ajax call detected');
return false;
}
else {
serial_token = $(this).serialize();
}
$.ajax({
url: 'validate.php',
type: 'POST',
cache: false,
timeout: 5000,
data: $theform.serialize(),
success: function(data) {
if (data=='' || !data || data=='-' || data=='ok') {
// something went wrong (ajax/response) or everything is ok, submit and continue to php validation
$('input[type=submit]',$theform).attr('disabled', 'disabled');
$theform.unbind('submit').submit();
} else {
// ajax/response is ok, but user input did not validate, so don't submit
console.log('test');
$('#jserrors').html('<p class="error">' + data + '</p>');
}
},
error: function(e) {
// something went wrong (ajax), submit and continue to php validation
$('input[type=submit]',$theform).attr('disabled', 'disabled');
$theform.unbind('submit').submit();
}
});
return false;
});
You could combine this with a timeout/interval function which aborts the submit, but the code above should just compare the data in the form
If you have some kind of submit button, just add a class 'disabled' to it when you start the ajax call, and check if it is present before trying to make the call. Remove the class when the server gives a response. Something like:
...
$theform = $(this);
$button = $theform.find('input[type=submit]');
if ($button.hasClass('disabled')) {
return false;
}
$button.addClass('disabled');
$.ajax({
....
},
complete: function () {
$button.removeClass('disabled');
}
});
...
When I click on the submit button of my form I'm redirected because of the PHP on the page "Form sent". How to stay in the same page with jQuery validate form plugin please ?
PHP FILE
<?php
// [I HAVE CUT THE CODE]
if(mail($to, $subject, $message, $headers)){
echo "Form sent";
} else {
echo "Form not sent";
}
?>
JQUERY FILE
$("#form-contact").validate({
submitHandler: function(form) {
$('.btn-validate-group:visible').hide();
$('.message-success').fadeIn(1000);
form.submit();
}
});
HTML FILE
<form id="form-contact" action="php/traitement.php" method="post"></form>
UPDATE 1
submitHandler: function(form) {
$('.btn-validate-group:visible').hide();
$('.message-success').fadeIn(1000);
$.ajax({
type: "POST",
url: url,
data: data,
success: function(result){ console.log("success!", result);},
dataType: dataType
});
return false;
}
I'm always redirected on "Form sent" page. I know nothing about Ajax :-/
UPDATE 2
http://jsfiddle.net/Xroad/2pLS2/25/
jQuery .ajax() can be used to submit data to the server without a page refresh, but it's not exclusive to the jQuery Validate plugin.
However, here are your two options using the jQuery Validate plugin.
Standard form submit using the default action of the form element (as you've done)...
$("#form-contact").validate({
submitHandler: function(form) {
$('.btn-validate-group:visible').hide();
$('.message-success').fadeIn(1000);
form.submit(); // standard submit of the default form action
}
});
To stay on same page, use .ajax() in the submitHandler callback...
$("#form-contact").validate({
submitHandler: function(form) {
$('.btn-validate-group:visible').hide();
$('.message-success').fadeIn(1000);
$.ajax({ // submit form using ajax
// your ajax options here
});
return false; // block default form action
}
});
See the jQuery .ajax() documentation for the options.
This is your own jsFiddle, which shows everything is working. I cannot test the ajax but the form is not refreshing the page as you claim.
If I understand correctly what you want, one way would be to try to submit from jQuery. In the submitHandler have something like:
$.ajax({
type: "POST",
url: url,
data: data,
success: function(result){ console.log("success!", result);},
dataType: dataType
});
The tricky part would be to get all the information into the data object before calling this.
The success function would have the data from the server after posting.
More info: https://api.jquery.com/jQuery.post/
If you make it work without validate plugin and more organised validation process then I would like you to have a look my code:
jQuery(document).ready(function($) {
$('#MyForm').on('submit', function(){
var form = this;
if(validateForm(form)) {
var values = $(form).serialize();
$.ajax({
url: "test.php",
type: "post",
data: values ,
success: function (response) {
// you will get response from your php page (what you echo or print)
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
event.preventDefault(); //changed to allow the tag manager to notice that the form was submitted
}
else{
event.preventDefault();
return false;
}
});
// validate Form
function validateForm(form) {
valid = true;
$(form).find('input[type=text], input[type=email]').each(function(i, val){
if(validateField(val, true) == false) { valid = false; }
});
return valid;
}
// validate all form fields
function validateField(field, submit) {
var val = $(field).val();
if($(field).attr('aria-required') == 'true' && submit){
if(val == '') {
$(field).parent().removeClass('valid');
$(field).parent().addClass('error');
return false;
}else {
$(field).parent().removeClass('error');
$(field).parent().addClass('valid');
return true;
}
// you can more specific
if($(field).attr('type') == 'text') {
$(field).parent().addClass('error');
return false; }
else {
$(field).parent().removeClass('error');
$(field).parent().addClass('valid');
return true;
}
// you can more specific
if($(field).attr('type') == 'email') {
$(field).parent().addClass('error');
return false; }
else {
$(field).parent().removeClass('error');
$(field).parent().addClass('valid');
return true;
}
}
}
// Run validation before Submit the form
$('input[type=text], input[type=email]').on('change', function(){
if($(this).val() != ''){
$(this).parent().removeClass('error valid');
validateField(this, false);
}
});
});
Is it possible to stop a form from submitting and then resubmitting the same form from within the success of an ajax call?
At the moment it gets to the success bit but it doesn't resubmit the form which should submit and redirect the user to the http://example.com website.
Thank you very much for any help in advance
If it's not possible to do it this way, is there another way of getting it to work?
$(document).ready(function() {
$('form').submit(function(e) {
e.preventDefault();
$.ajax({
url: $('form').attr('action'),
type: 'post',
data: $('form').serialize(),
success: function(data) {
if (data == 'true')
{
$('form').attr('action', 'http://example.com');
$('form').unbind('submit').submit(); // mistake: changed $(this) to $('form') - Problem still persists though it does not resubmit and redirect to http://example.com
}
else
{
alert('Your username/password are incorrect');
}
},
error: function() {
alert('There has been an error, please alert us immediately');
}
});
});
});
Edit:
Stackoverflow posts checked out for the code below:
Resume form submission after $.ajax call
How to reenable event.preventDefault?
I just thought I'd mention I have also tried this code without avail.
var ajaxSent = false;
$(document).ready(function() {
$('form').submit(function(e) {
if ( !ajaxSent)
e.preventDefault();
$.ajax({
url: $('form').attr('action'),
type: 'post',
data: $('form').serialize(),
success: function(data) {
if (data == 'true')
{
alert('submit form');
ajaxSent = true;
$('form').attr('action', 'http://example.com');
$('form').submit();
return true;
}
else
{
alert('Your username/password are incorrect');
return false;
}
},
error: function() {
alert('There has been an error, please alert us immediately');
return false;
}
});
});
});
I have also tried this code without any luck as well.
$(document).ready(function() {
$('form').submit(function(e) {
e.preventDefault();
$.ajax({
url: $('form').attr('action'),
type: 'post',
data: $('form').serialize(),
success: function(data) {
if (data == 'true')
{
$('form').attr('action', 'http://example.com');
$('form').unbind('submit').submit();
return true;
}
else
{
alert('Your username/password are incorrect');
return false;
}
},
error: function() {
alert('There has been an error, please alert us immediately');
return false;
}
});
});
});
Solution was quite simple and involved adding and setting async to false in .ajax(). In addition, I have re-worked the code to work of the submit button instead which submits the form when the AJAX passes successfully.
Here is my working code:
$(document).ready(function() {
var testing = false;
$('#btn-login').on('click', function() {
$.ajax({
url: $('form').attr('action'),
type: 'post',
data: $('form').serialize(),
async: false,
success: function(data) {
if (data == 'true')
{
testing = true;
$('form').attr('action', 'https://example.com');
$('form').submit();
}
else
{
alert('Your username/password are incorrect');
}
},
error: function() {
alert('There has been an error, please alert us immediately');
}
});
return testing;
});
});
It's no good practice to reselect all form tags throughout your code, what if you have multiple forms on the page?
Also you'd better use .on() and .off() with jQuery.
$(document).ready(function() {
$('form').on('submit', function(e) {
e.preventDefault();
// cache the current form so you make sure to only have data from this one
var form = this,
$form = $(form);
$.ajax({
url: form.action,
type: form.method,
data: $form.serialize(),
success: function(data) {
if (data == 'true')
{
$form.attr('action', 'http://example.com').off('submit').submit();
}
else
{
alert('Your username/password are incorrect');
}
},
error: function() {
alert('There has been an error, please alert us immediately');
}
});
});
});
In one line you use $('form') to select the form to change its action, but then you use $(this) to try to select that same form. I would guess that this inside the callback function isn't what you expect it to be, and is something other than your form (possibly the window object).
Just chain the calls:
$('form').attr('action', 'http://example.com').unbind('submit').submit();
I have a form that submits shopping cart data to a payment gateway (WorldPay) payment processing page. I need to perform a couple of extra logic the moment the custom decides to proceed to the payment but before the form submission itself. Basically, I simply want to generate a unique reference to the order at the very last moment.
Here is the jQuery code for the submit event:
$(function(){
$('#checkout-form').submit(function(e){
var $form = $(this);
var $cartIdField = $('#cartId');
console.log($cartIdField.val());
if($cartIdField.val() == ''){
e.preventDefault();
$.ajax({
url: baseUrl + '/shop/ajax/retrieve-shopping-cart-reference/',
data: {}, type: 'post', dataType: 'json',
success: function(json){
if(json.error == 0){
$('#cartId').val(json.data.cart_reference_number);
$form.submit();
}else{
alert(json.message);
}
}
});
}else{
console.log('Submitting form...'); //Does not submit!
}
});
});
The problem is that during the second submit triggered within the success: clause, the form isn't submitted still. I am assuming event.preventDefault() persists beyond the current condition.
How can I get around this?
For performe the any operation before form submit i used the following menthod hope it wil help
$('#checkout-form').live("submit",function(event){
//handle Ajax request use variable response
var err =false;
var $form = $(this);
//alert($form);
var values = {};
$.each($form.serializeArray(), function(i, field) {
values[field.name] = field.value;
});
//here you get all the value access by its name [eg values.src_lname]
var $cartIdField = $('#cartId');
console.log($cartIdField.val());
if($cartIdField.val() == ''){
$.ajax({
// your code and condition if condition satisfy the return true
// else return false
// it submit your form
/*if(condition true)
{
var err =true;
}
else
{
var err = false;
}*/
})
}
else
{
return true;
}
if(err)
{
return false
}
else
{
return true;
}
})
e.preventDefault() remove default form submit attribute which can not be reverted if applied once.
Use below code instead to prevent a form before submitting. This can be reverted.
$('#formId').attr('onsubmit', 'return false;');
And below code to restore submit attribute.
$('#formId').attr('onsubmit', 'return true;');
Only call e.preventDefault() when you really need to:
if(not_finished_yet) {
e.preventDefault();
}
I have email field in user's settings area. All emails are unique, of course, so I need to check is email not used already by someone else before submitting the form.
Here is the code:
var email = $("input#email-id").val();
$("#form-id").submit(function(){
$.ajax({
url: "/ajax/email?email=" + email,
success: function(data){
if(data != 'ok'){
alert("Email is used already");
return false;
}
}
});
});
So, if data is not 'ok' it must destroy submitting the form because if() returns false, but it doesn't and the form submits as usual and even alert doesn't appear!
I've checked ajax answer and it works fine (returns 'user_already' if email is used).
So what I did wrong?
Thanks!
Since ajax is async by nature you cannot do that. If you really want to do that you can submit the form inside the success handler. Try this.
function submitHandler(){
var email = $("input#email-id").val();
$.ajax({
url: "/ajax/email?email=" + email,
success: function(data){
if(data != 'ok'){
alert("Email is used already");
return false;
}
else{
//Once the data is ok you can unbind the submit handler and
//then submit the form so that the handler is not called this time
$("#form-id").unbind('submit').submit();
}
}
});
return false;//This will prevent the form to submit
}
$("#form-id").submit(submitHandler);
It's because the Ajax request to check the email is asynchronous. It will not complete before the submit event handler is finished. You'd have to do something like this:
$('#form-id').submit(function() {
if($(this).data('valid')) {
//you've already validated, allow the form to submit
return true;
} else {
//send an ajax request and wait for the response to really submit
$.ajax({
url: "/ajax/email?email=" + email,
success: function(data){
if(data == 'ok') {
//submit the form again, but set valid data so you don't do another Ajax request
$('#form-id').data('valid', true);
$('#form-id').submit();
} else {
alert("Email is used already");
}
}
});
return false;
}
//clear the validation flat
$(this).data('valid', false);
});
There's an accepted answer but I thought I'd share another way to do this.
You can use an extra parameter with the .trigger() function to first test the user's email, and if it comes back available then re-trigger the submit event but set a flag to not check the username:
$("#form-id").submit(function(event, forceSubmit){
//the normal submit will not have the extra parameter so we need to initialize it to not throw any errors,
//typeof is great for this since it always returns a string
if (typeof(forceSubmit) == 'undefined') { forceSubmit = false; }
//now check if this is a normal submit or flagged to allow submission
if (forceSubmit === false) {
var $form = $(this);
$.ajax({
url: "/ajax/email?email=" + email,
success: function(data){
if(data != 'ok'){
alert("Email is used already");
} else {
$form.trigger('submit', true);
}
}
});
//since this submit event is for checking the username's availability we return false to basically: event.preventDefault(); event.stopPropagation();
return false;
}
});
.trigger(): http://api.jquery.com/trigger
In your code you have two functions. One is the function passed to submit:
$("#form-id").submit(function() {
// code
});
The other is the function passed to the success handler of the AJAX call:
success: function(data) {
// code
}
You are returning false from the second function. This means that when the first function returns, it is not returning false. But the form submission is stopped, only if the first function returns false.
What you should do is to make the function passed to submit always return false and handle submission programmatically.
This code helps you to achieve this:
var submitHandler = function() {
$.ajax({
url: "/ajax/email?email=" + email,
success: function(data) {
if (data != 'ok') {
alert("Email is used already");
// no need to do anything here
} else {
// success, we should submit the form programmatically
// first we de-attach the handler, so that submitHandler won't be called again
// and then we submit
$("#form-id").unbind('submit').submit();
// now we reattach the handler, so that submit handler is executed if the user
// submits the form again
$("#form-id").submit(submitHandler);
}
}
});
// always return false, because if validation succeeds, we will submit the
// form using JavaScript
return false;
};
$("#form-id").submit(submitHandler);
I already +1 #ShankarSangoli because he got it right however, I don't feel its 100% complete as there is also an error state that can occur upon network issues or server fault.
$('#form-id').submit(function(ev) {
ev.preventDefault(); // cancels event in jQuery typical fashion
$.ajax({
url: "/ajax/email",
data : { email: $("input#email-id").val()},
success : function(d) {
if (d !== 'ok') {
alert('email in use');
}
},
error : function(a,b,c) {
// put your error handling here
alert('a connection error occured');
}
});
});
There are even better ways to handle this as I've written some great form plugins for jQuery that are HTML5 compliant and rival jQuery tools for ease of use.
You can see an example here -> http://www.zipstory.com/signup
Happy coding.
If JSON is involved, the returned data is in data.d - see http://encosia.com/a-breaking-change-between-versions-of-aspnet-ajax/ for an explanation.