Jump to content

help, Ajax php .post() return variable scope


xekon

Recommended Posts

I have been working on my registration page for the last couple days, I just about have it finished and I hit a snag. If I call the below function from another function, the return value remains undefined because I believe it is out of scope, I tried a simple Return 1 or Return 0. then I tried using a variable so I could better see what was happening. It seems the variables within .post() lose scope? at the end of the function rval is still undefined. Is there another way to handle the variable, or a workaround?

function check_usern(){var op = "checkuser";var usern = $("#usern").val();var passworda = $("#passworda").val();var rval;if(usern.length >= 2){  $("#ustatus").html('<img src="inc/loader.gif"> Checking availability...');  $.post('inc/user-man.php',{op:op,user:usern,pass:passworda},function(data){   if(data == 'Available')   {	rval = 1	$("#usern").removeClass('object_error'); // if necessary	$("#usern").addClass("object_ok");	$('#ustatus').html(' <img src="inc/tick.gif">');   }   else if(data == 'Unavailable')   {	rval = 0	$("#usern").removeClass('object_ok'); // if necessary	$("#usern").addClass("object_error");	$("#ustatus").html('<font color="red">Username <b>' + usern + '</b> is unavailable.</font>');   }   else   {	rval = 0	$("#usern").removeClass('object_ok'); // if necessary	$("#usern").addClass("object_error");	$('#ustatus').html(data);     }  });}else{  $("#ustatus").html('<font color="red">Username should have <strong>2+</strong> characters.</font>');  $("#usern").removeClass('object_ok'); // if necessary  $("#usern").addClass("object_error");  //rval = 0// this one works if uncommented, its just the ones within .post() that lose scope}return rval}

I have a function to validate each field. as you go from field to field, .change()/.focus()/.blurThen when the user clicks submit I would like it to validate all fields by calling all the different functions, and if they pass validation, submit the data to user-man.php for insertion into the database. I have not done a ton of web design, if you have any suggestions for me please let me know. also here is the complete code for the page for anyone curious (there are no html,head,body tags because this page is loaded through index as an include):

<center><div align="center">  <form>   <table width="600" border="0">	<tr>	 <td width="150"><div align="right">Username: </div></td>	 <td width="100"><input id="usern" size="20" maxlength="20" type="text" name="usern"></td>	 <td align="left"><div id="ustatus"></div></td>	</tr>	<tr>	 <td width="150"><div align="right">Password: </div></td>	 <td width="100"><input id="passworda" size="20" maxlength="40" type="password" name="passworda"></td>	 <td align="left"><div id="pstatus"></div></td>	</tr>	<tr>	 <td width="150"><div align="right">Confirm Password: </div></td>	 <td width="100"><input id="confirm_password" size="20" maxlength="40" type="password" name="confirm_password"></td>	 <td align="left"><div id="cpstatus"></div></td>	</tr>	<tr>	 <td width="150"><div align="right">Email: </div></td>	 <td width="100"><input id="email" size="20" maxlength="50" type="text" name="email"></td>	 <td align="left"><div id="estatus"></div></td>	</tr>	<tr>	 <td width="150"><div align="right">Gender: </div></td>	 <td width="100"><input id="gender" type="radio" name="gender" value="male">Male   <input id="gender" type="radio" name="gender" value="female">Female</td>	 <td align="left"><div id="gstatus"></div></td>	</tr>	<tr>	 <td width="150"><div align="right">Date of Birth: </div></td>	 <td width="100"><input id="date" name="date" size="10" maxlength="10" type="textbox" value="mm/dd/yyyy"/>   </td>	 <td align="left"><div id="bstatus"></div></td>	</tr>	<tr>	 <td width="250" colspan="2"> I agree to the Terms of Use & Privacy Policy <input id="termpriv" type="checkbox" name="termpriv" value="Yes"></td>	 <td align="left"><div id="tpstatus"></div></td>	</tr>	<tr>	 <td width="250" align="right" colspan="2"><button type="button" id="create" name="create" value=" Register "> Register </button></td>	 <td align="left"><div id="cstatus"></div></td>	</tr>   </table>  </form></div></center><script type="text/javascript">pic1 = new Image(16, 16);pic1.src = "inc/loader.gif";$(document).ready(function(){$('#create').click(create_user);$('#usern').change(check_usern);$('#passworda').change(check_password);$('#passworda').focus(check_password);$('#confirm_password').blur(check_confirm_password);$('#confirm_password').focus(check_confirm_password);$('#email').change(check_email);$("input[name=date]").focus(function(){  if($(this).val() === "mm/dd/yyyy"){   $(this).val('');  }});$("input[name=date]").blur(function(){  if($(this).val() === ""){   $(this).val('mm/dd/yyyy');  }});$("#date").datepicker({  changeMonth: true,  changeYear: true,  yearRange: "-120:+0"});});function create_user(){if(check_usern() != 1){  $('#cstatus').html('check_usern: '+check_usern());  return 0}else if(check_password() != 1){  $('#cstatus').html('check_password');  return 0}else if(check_confirm_password() != 1){  $('#cstatus').html('check_confirm_password');  return 0}else if(check_email() != 1){  $('#cstatus').html('check_email');  return 0}else{  var op = "new";  var usern = $("#usern").val();  $("#cstatus").html('<img src="inc/loader.gif"> Registering...');  $.post('inc/user-man.php',{op:op,user:usern},function(data){   if(data == 'Available')   {	$('#cstatus').html(' <img src="inc/tick.gif">');   }   else//should be used for failed ajax .post, all other possible outcomes should be covered above   {	$('#cstatus').html(data);   }  });}}function check_usern(){var op = "checkuser";var usern = $("#usern").val();var passworda = $("#passworda").val();var rval;if(usern.length >= 2){  $("#ustatus").html('<img src="inc/loader.gif"> Checking availability...');  $.post('inc/user-man.php',{op:op,user:usern,pass:passworda},function(data){   if(data == 'Available')   {	rval = 1	$("#usern").removeClass('object_error'); // if necessary	$("#usern").addClass("object_ok");	$('#ustatus').html(' <img src="inc/tick.gif">');   }   else if(data == 'Unavailable')   {	rval = 0	$("#usern").removeClass('object_ok'); // if necessary	$("#usern").addClass("object_error");	$("#ustatus").html('<font color="red">Username <b>' + usern + '</b> is unavailable.</font>');   }   else   {	rval = 0	$("#usern").removeClass('object_ok'); // if necessary	$("#usern").addClass("object_error");	$('#ustatus').html(data);     }  });}else{  $("#ustatus").html('<font color="red">Username should have <strong>2+</strong> characters.</font>');  $("#usern").removeClass('object_ok'); // if necessary  $("#usern").addClass("object_error");  //rval = 0// this one works if uncommented, its just the ones within .post() that lose scope}return rval}function check_password(){var op = "checkpass";var usern = $("#usern").val();var passworda = $("#passworda").val();if(passworda == ''){  //do nothing}else if(passworda.length >= 4){  //$("#pstatus").html('<img src="inc/loader.gif"> Checking availability...');  $.post('inc/user-man.php',{op:op,user:usern,pass:passworda},function(data){   //if(data == 'OK')   if(data.indexOf("OK") != -1)   {	$("#passworda").removeClass('object_error'); // if necessary	$("#passworda").addClass("object_ok");	$('#pstatus').html(' <img src="inc/tick.gif">');	return 1   }   else if(data.indexOf("classes") != -1)   {	$("#passworda").removeClass('object_ok'); // if necessary	$("#passworda").addClass("object_error");	$('#pstatus').html('<font color="red">password must have 2+ numbers/symbols</font>');   }   else if(data.indexOf("short") != -1)   {	$("#passworda").removeClass('object_ok'); // if necessary	$("#passworda").addClass("object_error");	$('#pstatus').html('<font color="red">password must be 8+ characters long</font>');   }   else//should be used for failed ajax .post, all other possible outcomes should be covered above   {	$("#passworda").removeClass('object_ok'); // if necessary	$("#passworda").addClass("object_error");	$('#pstatus').html('<font color="red">'+data+'</font>');   }  });}else{  $("#pstatus").html('<font color="red">The password should have at least <strong>4</strong> characters.</font>');  $("#passworda").removeClass('object_ok'); // if necessary  $("#passworda").addClass("object_error");}return 0}function check_confirm_password(){var passworda = $("#passworda").val();var confirm_password = $("#confirm_password").val();if(passworda == '' || confirm_password == ''){  //do nothing}else if(passworda == confirm_password){  $("#confirm_password").removeClass('object_error'); // if necessary  $("#confirm_password").addClass("object_ok");  $('#cpstatus').html(' <img src="inc/tick.gif">');  return 1}else{  $("#cpstatus").html('<font color="red">Passwords do not match.</font>');  $("#confirm_password").removeClass('object_ok'); // if necessary  $("#confirm_password").addClass("object_error");}return 0}function check_email(){var email = $("#email").val();var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;if(!emailReg.test(email)){  $("#email").removeClass('object_ok'); // if necessary  $("#email").addClass("object_error");  $('#estatus').html('<font color="red">Please enter a valid email address</font>');} else {  $("#email").removeClass('object_error'); // if necessary  $("#email").addClass("object_ok");  $('#estatus').html(' <img src="inc/tick.gif">');  return 1}return 0}</script>

Edited by xekon
Link to comment
Share on other sites

Typically ajax requests are asynchronous, meaning that the check_usern function will finish and return before the request to user-man.php is finished, it does not wait for that request to finish before the function ends. That's what the callback functions are for, the callback will run when the request finishes. Instead of returning rval from the outer function, you need to call another function from inside the callback and send it the value of rval.

  • Like 1
Link to comment
Share on other sites

Thank you so much :) worked perfect:

function create_user(){var allclear = 'go';check_user(function(rval) {//should fire when callback function is called  if(rval != 1)  {   allclear='check_user: '+rval;  }});if(check_password() != 1) {  allclear=allclear+' check_password ';} else if(check_confirm_password() != 1) {  allclear=allclear+' check_confirm_password ';} else if(check_email() != 1) {  allclear=allclear+' check_email ';} else if(check_gender() != 1) {  allclear=allclear+' check_gender ';} else if(check_dob() != 1) {  allclear=allclear+' check_dob ';} else if(check_termpriv() != 1) {  allclear=allclear+' check_termpriv ';}if(allclear != 'go'){  $("#cstatus").html('<font color="red">error: <b>'+allclear+'</b></font>');}else{  //no errors found, should be good to go  var op = "new";  var user = $("#user").val();  var pass = $("#pass").val();  $("#cstatus").html('<img src="inc/loader.gif"> Registering...');  $.post('inc/user-man.php',{op:op,user:user,pass:pass},function(data){   if(data == 'Available')   {	$('#cstatus').html(' <img src="inc/tick.gif">');   }   else//should be used for failed ajax .post, all other possible outcomes should be covered above   {	$('#cstatus').html(data);   }  });}}function check_user(callback) {var op = "checkuser";var user = $("#user").val();var pass = $("#pass").val();if(user.length >= 2){  $("#ustatus").html('<img src="inc/loader.gif"> checking availability...');  $.post('inc/user-man.php',{op:op,user:user,pass:pass},function(data){   if(data == 'Available')   {	$("#user").removeClass('object_error'); // if necessary	$("#user").addClass("object_ok");	$('#ustatus').html(' <img src="inc/tick.gif">');	callback(1);//callback function   }   else if(data == 'Unavailable')   {	$("#user").removeClass('object_ok'); // if necessary	$("#user").addClass("object_error");	$("#ustatus").html('<font color="red">username <b>' + user + '</b> is unavailable.</font>');   }   else   {	$("#user").removeClass('object_ok'); // if necessary	$("#user").addClass("object_error");	$('#ustatus').html(data);   }  });}else{  $("#ustatus").html('<font color="red">username must have <b>2+</b> characters.</font>');  $("#user").removeClass('object_ok'); // if necessary  $("#user").addClass("object_error");}}

Edited by xekon
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...