Javascript does user exists, returning value from ajax to late? -
i have script tells visitor if username exist or not before can proceed, below see part of code;
edit: ok have read guys said, , modified it, still dont work :s, teacher doesn't know either...
<script type="text/javascript"> jquery(document).ready(function(){ // smart wizard jquery('#wizard').smartwizard({onfinish: onfinishcallback, onleavestep: onnextstep}); function onnextstep(){ validatesteps(function (next) { return next; }); } function onfinishcallback(){ alert('finish clicked'); } function usernameexist(fullname, callback) { var data = 'user='+ fullname; if(fullname) { $.ajax({ type: "post", url: "user_check.php", data: data, async: false, beforesend: function(html) { $("#msg_lastname").html(''); }, success: function(html){ $("#msg_lastname").show(); $("#msg_lastname").append(html); if(html.search("red") != -1) { callback(false); } else { callback(true); } } }); } } function validatesteps(callback){ var isstepvalid = true; // validate step 1 var firstname = $('#firstname').val(); if(!firstname || (firstname.length < 3 || firstname.length > 10)) { $('#msg_firstname').html('<br/><font color="red">enter first name, between 3 , 10 letters.</font>').show(); isstepvalid = false; } else { $('#msg_firstname').html('').hide(); } var lastname = $('#lastname').val(); if(!lastname || (lastname.length < 3 || lastname.length > 14)) { $('#msg_lastname').html('<br/><font color="red">enter last name, between 3 , 14 letters.</font>').show(); isstepvalid = false; } else { $('#msg_lastname').html('').hide(); } var gender = $('#gender').val(); if(!gender || number(gender) == -1) { $('#msg_gender').html('<br/><font color="red">choose gender!</font>').show(); isstepvalid = false; } else { $('#msg_gender').html('').hide(); } var age = $('#age').val(); if(!age || number(age) > 90 || number(age) < 21) { $('#msg_age').html('<br/><font color="red">enter age between 21 , 90.</font>').show(); isstepvalid = false; } else { $('#msg_age').html('').hide(); } var pin = $('#pin').val(); if(!pin || pin.length > 10 || pin.length < 4) { $('#msg_pin').html('<br/><font color="red">enter pin between 4 , 10 numbers.</font>').show(); isstepvalid = false; } else { $('#msg_pin').html('').hide(); } if (isstepvalid) { usernameexist(firstname + ' ' + lastname, function (exists) { callback( exists ); }); } else { callback( false ); } } jquery('select, input:checkbox').uniform(); }); </script>
now problem when run script, returns undefined, guess because usernameexist not done fast enough, , seems return usernameexist not waiting for reason...
you returning usernameexists
before has been run.
instead, call usernameexists
this:
if (isstepvalid) { usernameexist(firstname + ' ' + lastname, function (exists) { return exists; }); } else { return false; }
this works because usernameexists
expects callback function , on success passes either true
or false
callback()
.
Comments
Post a Comment