Having Following form validation through jQuery:
$("#Login").submit(function( event ) {
var url = 'ajax/';
var data = {};
$("input").each(function() {
data[$(this).attr('name')] = $(this).val();
});
$.post(url,data,function( resp ) {
$("#formLoginErrorMessage").children().remove();
if(resp === " ")
{
console.log("Empty");
return; // The form should submit
} else if (typeof resp === "object") {
console.log(resp);
} else{
$("#formLoginErrorMessage").addClass("alert-danger");
$("#formLoginErrorMessage").append("<li>" + resp + "</li>");
console.log(resp);
}
},'json');
event.preventDefault();
});
This script is checking some errors and when resp is empty form should submit. But return from if where resp is checked doesn't seem to make form submit.
You can call the submit() method in the if condition
$("#Login").submit(function (event) {
var form = this;
var url = 'ajax/';
var data = {};
$('input').each(function () {
data[$(this).attr('name')] = $(this).val();
});
$.post(url, data, function (resp) {
$("#formLoginErrorMessage").children().remove();
if (resp === " ") {
form.submit();
console.log("Empty");
return; // The form should submit
} else if (typeof resp === "object") {
console.log(resp);
} else {
$("#formLoginErrorMessage").addClass("alert-danger");
$("#formLoginErrorMessage").append("<li>" + resp + "</li>");
console.log(resp);
}
}, 'json');
event.preventDefault();
});
What you seem to be confused about are closures
$( "#Login" ).submit(function( event ) {
// main submit handling function starts here
...
$.post(url,data,function(resp){
// inner response handling function starts here
if(resp === " "){
console.log("Empty");
return; //This returns to jQuery internals somewhere inside $.post
} ...
},'json');
// stops form from submitting
event.preventDefault();
});
I added a couple of comments to help you get a better visual of the scope.
First thing first, you should never rely on client-side validation. It can be overtaken without exceptions. If for some reason you insist on having it this way you can use some outer scope variable to determine whether validation has passed or not, but then you have to use $form.submit() instead of return to actually submit the form.
Related
<script type="text/javascript">
//$('#student').change(function() {
$('#but').click(function() {
var payid = $("#feType").val();
var course = $("#course").val();
var course_id = $("#course_id").val();
var stud_id = $("#student").val();
var paid_amt1 = $("#paid_amt").val();
var serializedData = $("form").serialize();
$.ajax({
dataType: "json",
url: '<?php echo ADMINPATH;?>student/getNewFee/'+payid+'/'+course_id+'/'+stud_id+'/'+course,
data: '',
async: true,
success: function(data){
if(data == false){
$("form").unbind('submit').submit();
alert("This student doesn't have transport");
return false;
}
var result = data;
if(Number(result) >= Number(paid_amt1)){
$("#fee_data").submit(function(){
return true;
});
}else {
$("form").unbind('submit');
alert("Due Amount is less than paid amount");
return false;
}
}
});
});
</script>
If the data is coming to if condition the form has to submit, and if data is coming to else condition form submitting should stop. "if" condition is working well, but coming to else the form is still getting submitted.
You are calling submit() method from else portion.
Remove below code from else portion.
$("form").unbind('submit').submit();
Remove this line, it is not needed and you are triggering the submit with it:
$("form").unbind('submit').submit();
If you only want to remove the on submit callback, you can do this:
$("form").unbind('submit');
You need to add a return false before the end of the click event:
$('#but').click(function() {
// ....
return false;
});
I have a form and a piece of javascript code to create AJAX forms. The weird thing is when i submit my form in Internet Explorer the only thing that displays is [object Object]. The form works fine in Google Chrome. Here is my code:
Form header:
<form id="page-details-form" class="ajax-form" name="page-details-form" method="POST" action="/pages/save/1">
Javascript listener:
<script>
$(function(){
$(document).on("submit",".ajax-form",function(e){
if (window.event) {
window.event.returnValue = false;
}
e.preventDefault ? e.preventDefault() : e.returnValue = false;
$('.form-message').remove();
if($('#onSubmitJsEval').html() && $('#onSubmitJsEval').html().length > 0)
{
eval($('#onSubmitJsEval').html());
}
var submitBtnValue = $('#submitBtn').html();
var formId = $(this).attr('id');
var postData = $(this).serializeArray();
$('#submitBtn') .html('<img src="images/ajax-loader.gif" />');
$('p.has-error') .remove();
$('div.has-error') .removeClass('has-error');
$.post($(this).attr('action'), postData, function(jsonResponse)
{
var jsonObject = jQuery.parseJSON(jsonResponse);
if(jsonObject.success == true)
{
$('<div class="<?=MESSAGE_SUCCESS_CLASS?>"><?=MESSAGE_SUCCESS_PREFIX?>'+jsonObject.message+'</div>' ).insertBefore( "#" + formId + " h2" );
if(jsonObject.insertedId > 0)
{
var stringPath = window.location.pathname.substr(window.location.pathname.length - 1);
document.location.href = window.location.pathname + ((stringPath != "/") ? "/" : "") + jsonObject.insertedId;
}
}
else
{
$('<div class="<?=MESSAGE_ERROR_CLASS?>"><?=MESSAGE_ERROR_PREFIX?>'+jsonObject.message+'</div>' ).insertBefore( "#" + formId + " h2" );
$.each(jsonObject.errors, function(index, value){
$('[name='+index+']').parent().addClass('has-error');
$('[name='+index+']').after('<p class="has-error help-block">'+value+'</p>');
})
}
$('#submitBtn').html(submitBtnValue);
});
});
});
</script>
I tried several options besides the current option:
if (e.preventDefault) e.preventDefault();
e.returnValue = false
e.returnValue = false after e.preventDefault
Does anyone have a idea? If i need to publish more code please let me know. I can post all the code if you want.
Many thanks!
You will need a combination of e.preventDefault() and return false, with handling code inbetween.
$(document).on("submit", ".ajax-form", function(e) {
e.preventDefault();
//Do your stuff here
return false;
});
I am using twitter bootstrap and I have a birthday Modal which asks user to enter their date of birth, the validation and inserting the data into database is working fine but i need to redirect user to another page (dashboard.php) on success, following is the ajax code i am using
$('#dobform').submit(function (e) {
"use strict";
e.preventDefault();
$('#dobsubmit').button('loading');
var post = $('#dobform').serialize();
var action = $('#dobform').attr('action');
$("#message").slideUp(350, function () {
$('#message').hide();
$.post(action, post, function (data) {
$('#message').html(data);
document.getElementById('message').innerHTML = data;
$('#message').slideDown('slow');
if (data.match('success') !== null) {
$('#dobform').slideUp('slow');
$('#dobsubmit').button('complete');
$('#dobsubmit').click(function (eb) {
eb.preventDefault();
$('#dob-form').modal('hide');
});
}
else {
$('#dobsubmit').button('reset');
}
});
});
});
I have tried using the following redirection code in else but it redirects the user regardless of error or not
window.location = "dashboard.php"
I have tried using the redirection inside
if (data.match('success') !== null) {
}
but this does not work either, I would really appreciate any help.
Finally managed to do it, had to take out match
$('#dobform').submit(function (e) {
"use strict";
e.preventDefault();
$('#dobsubmit').button('loading');
var post = $('#dobform').serialize();
var action = $('#dobform').attr('action');
$("#message").slideUp(350, function () {
$('#message').hide();
$.post(action, post, function (data) {
$('#message').html(data);
document.getElementById('message').innerHTML = data;
$('#message').slideDown('slow');
if (data == "Thankyou") {
$('#dobform').slideUp('slow');
$('#dobsubmit').button('complete');
window.location = "dashboard.php";
$('#dobsubmit').click(function (eb) {
eb.preventDefault();
$('#dob-form').modal('hide');
});
}
else {
$('#dobsubmit').button('reset');
}
});
});
});
So I'm creating this form validator with PHP and jQuery.
The PHP code will check through the form and then return an array with fields that contain errors. Example: {"email":1,"password":1}
But now I have concerns regarding if no errors were to be found. The problem here is that I've included "return false" in the end of the code to prevent page redirection. I've read that this is bad code practice but not found another way that works as intended.
The second problem is how to pass the o-array into the $('input').each function. Right now it will say that all forms are valid since nothing was passed. If I use $.post instead of $.ajax this scope problem doesn't appear for some reason.
jQuery:
$(function() {
$('#register').submit(function() {
var url = $(this).attr('action');
var data = $(this).serialize();
$.ajax({
type: 'GET',
url: url,
data: data,
success: function(o) {
console.log(o);
$('input').each(function() {
var msgId = o[$(this).attr('name')];
console.log(o[$(this).attr('name')]);
if (msgId > 0) {
$('#listError').css('visibility', 'visible');
$('#listError').append('<li>' + $(this).nextAll('span.msg').eq(msgId - 1).text() + '</li>');
$(this).addClass('invalid');
} else if (msgId != 0) {
$(this).addClass('valid');
}
$('#listError').append('</ul>');
})
}
}, 'json');
return false;
});
});
Fist, why are you submitting a form when you really don't want to?! Use a button instead and make the AJAX request from its click handler.
$('#registerButton').click(function() {
var form = $('#register')
var data = form.serialize();
$.ajax(...);
});
"The second problem is how to pass the o-array into the $('input').each"
What is the problem here? If you have an each() inside a success callback, you can use the data parameter that is passed to the callback (or o in your case) in that each().
Try this
$(function() {
$('#submit_button_id').click(function() {
var url = $(this).attr('action');
var data = $(this).serialize();
var ret = true;
$.ajax({
type: 'GET',
url: url,
async: false,
data: data,
success: function(o) {
console.log(o);
$('input').each(function() {
var msgId = o[$(this).attr('name')];
console.log(o[$(this).attr('name')]);
if (msgId > 0)
ret = false;
$('#listError').css('visibility', 'visible');
$('#listError').append('<li>' + $(this).nextAll('span.msg').eq(msgId - 1).text() + '</li>');
$(this).addClass('invalid');
} else if (msgId != 0) {
$(this).addClass('valid');
}
$('#listError').append('</ul>');
})
}
}, 'json');
if(ret==true){
$('#register').submit();
}
});
});
still looking for a solution but not find yet, I have a function to manage different forms on same/differents pages
function formStantardAction(correctAnswer,addCustomData){
addCustomData = (typeof addCustomData == "undefined")?'':addCustomData;
correctAnswer = (typeof correctAnswer == "undefined")?'Saved.':correctAnswer;
$('form.standard').submit(function(event){
event.preventDefault();
var modalWin = $(this).parent();
var values = $('form.standard').serialize() + addCustomData;
$.ajax({
url: "inc/gateway.php",
data: values,
type: "POST",
success: function(data){
if (data == "OK"){
$(modalWin).html(correctAnswer).delay(500).fadeOut(500);
setTimeout(function() {
mw_close();
}, 1000);
}else{
alert(data);
}
}
});
});
}
after loaded the page and form with an input type="button" named SEND
$('form.standard [name="SEND"]').click(function(){
var str = $('#sortableTo').serializelist();
formStantardAction('New train inserted.',str);
$('form.standard').submit();
});
all the values reach a php page via POST that made all the things (validating, insert in db, update log...) and answer with 'OK' if all OK (so the form in the modal window is substituted with custom message and fade out) or... if there is an error, php answer with some text that js popups with an alert keeping the modal window open with the form.
It's all ok BUT, if php answer with an error, with second click of button SEND the post is sent 2 times.
And if I make another error on second send, and click again the send button, the post values is sent three time... and so on.
What can I do? Where is my error?
thanks.
Try excluding submit block:
function formStantardAction(correctAnswer,addCustomData){
addCustomData = (typeof addCustomData == "undefined")?'':addCustomData;
correctAnswer = (typeof correctAnswer == "undefined")?'Saved.':correctAnswer;
//$('form.standard').submit(function(event){
// event.preventDefault();
//change 'this' to form.standard
var modalWin = $('form.standard').parent();
var values = $('form.standard').serialize() + addCustomData;
$.ajax({
url: "inc/gateway.php",
data: values,
type: "POST",
success: function(data){
if (data == "OK"){
$(modalWin).html(correctAnswer).delay(500).fadeOut(500);
setTimeout(function() {
mw_close();
}, 1000);
}else{
alert(data);
}
}
});
});
// }
and after loaded page:
$('form.standard [name="SEND"]').click(function(){
var str = $('#sortableTo').serializelist();
formStantardAction('New train inserted.',str);
//excluding submit event
// $('form.standard').submit();
});
Because $.ajax {} with type:"Post" is already a submit process and then when script call submit then it re-submit.
Hope this right and help
Is it possbile that somewhere in your code you bind the submit event to the form everytime you get the data back from the ajax-request?
I can't check this in the code you submitted here.
Create a global variable as flag
var flag = 0;
and check this flag while posting and reset it after completed
function formStantardAction(correctAnswer,addCustomData){
**if(flag == 1){
return false;
}
flag = 1;**
addCustomData = (typeof addCustomData == "undefined")?'':addCustomData;
correctAnswer = (typeof correctAnswer == "undefined")?'Saved.':correctAnswer;
$('form.standard').submit(function(event){
event.preventDefault();
var modalWin = $(this).parent();
var values = $('form.standard').serialize() + addCustomData;
$.ajax({
url: "inc/gateway.php",
data: values,
type: "POST",
success: function(data){
**flag = 0;**
if (data == "OK"){
$(modalWin).html(correctAnswer).delay(500).fadeOut(500);
setTimeout(function() {
mw_close();
}, 1000);
}else{
alert(data);
}
}
});
});
}
I put some custom code at the beginning of your submit function - basically if a submit is in progress nothing should be done, but otherwise return an error message as usual.
var submitting = false; //initialise the variable, this needs to be out of the function!
function formStantardAction(correctAnswer,addCustomData){
addCustomData = (typeof addCustomData == "undefined")?'':addCustomData;
correctAnswer = (typeof correctAnswer == "undefined")?'Saved.':correctAnswer;
$('form.standard').submit(function(event){
if (submitting) {
return false; //if a submit is in progress, prevent further clicks from doing anything
} else {
submitting = true; //no submit in progress, but let's make one now
}
event.preventDefault();
var modalWin = $(this).parent();
var values = $('form.standard').serialize() + addCustomData;
$.ajax({
url: "inc/gateway.php",
data: values,
type: "POST",
success: function(data){
if (data == "OK"){
$(modalWin).html(correctAnswer).delay(500).fadeOut(500);
setTimeout(function() {
mw_close();
}, 1000);
}else{
alert(data);
}
}
});
});
}