Jquery: Error test after Ajax function -
again, have tried searching prevent duplicate think error due poor jquery level.
my registration form uses following jquery:-
$(document).ready(function() { $('form#registration').submit(function() { $('form#registration .error').remove(); var haserror = false; $('.requiredfield').each(function() { if($.trim($(this).val()) == '') { var labeltext = $(this).prev('label').text(); $(this).parent().append('<span class="error">you forgot enter '+labeltext+'</span>'); $(this).addclass('inputerror'); haserror = true; } else if($(this).hasclass('email')) { var emailreg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/; if(!emailreg.test($.trim($(this).val()))) { var labeltext = $(this).prev('label').text(); $(this).parent().append('<span class="error">you have entered invalid '+labeltext+'</span>'); $(this).addclass('inputerror'); haserror = true; } else { $.ajax({ type: "post", data: "email="+$(this).attr("value"), url: "emailexists.php", context: this, success: function(data) { if(data == 1) { $(this).parent().append('<span class="error">this email exists on file</span>'); haserror = true; } } }); } } else if($(this).hasclass('password')) { var regx = /^[a-za-z0-9]+$/; if(!regx.test($.trim($(this).val()))) { $(this).parent().append('<span class="error">password can contain alphanumerica characters a-za-z0-9</span>'); haserror = true; } var passlen = $.trim($(this).val().length); if(passlen < 7) { $(this).parent().append('<span class="error">password must @ least 7 characters in length</span>'); haserror = true; } } else if($(this).hasclass('cpassword')) { if($(this).val() != $('#password').val()) { $(this).parent().append('<span class="error">your passwords not match</span>'); haserror = true; } } }); **if(!haserror) { var forminput = $(this).serialize(); $.post($(this).attr('action'),forminput, function(data) { $('form#registration').slideup("fast", function() { $(this).before('<p class="tick">thank registering <font style="color:#ddbb88;">racingdatasheets.com</font>. should receive confirmation email shortly.</p>');** }); }); } return false; }); });
my issue error test @ bottom returns false if other tests pass before ajax emailexists function returns possible error. (i added 2 alerts , see error check @ bottom testing false prior emailexists setting haserror true. misunderstanding asynchronous nature of ajax , doing wrong?
any appreciated.
you have think order of operations..
you have 5 statements executed when form submitted, 1 after other.
inside $('.requiredfield').each(function() {
sending ajax requests, asynchronous, continuing synchronously , inspecting result (haserror
). unlikely have been set before line if(!haserror) {
executed.
what store requests in array , user jquery.when check haserror
once have completed, this:
var requests = []; ... requests.push($.ajax(...)) ... $.when(requests).then(function () { if (!haserror) { ... } });
Comments
Post a Comment