javascript/jQuery setTimeout and clearTimeout not working - php

This is a total noob problem. Sorry. I am using jQuery and ajax with php backend to check availability of usernames on keyup. I have this in my form.
Username <input id="uName" type="text" maxlength="20" name="username" /><br />
<span id="uNMessage"> </span>
and this in my script
function unchk(){
$('#uName').keyup(function(){
var ab = $(this);
if(ab.val().length > 4){
$.ajax({url: "/php/username-check.php",type:'post',data:{username:$(this).val()},
success: function(result){
if(result == 0){
ab.css("outline-color","red");
untmr('Username Already Taken');
}
else if(result == 1){
ab.css("outline-color","#42c43b");
$('#uNMessage').html(' ');
}
}
});
}
else{
$(this).css("outline-color","red");
}
});
}//END FUNCTION UNCHK
function untmr(msg){
clearTimeout(unto);
unto = setTimeout(unmsg(msg),1500);
}
function unmsg(msg){
$('#uNMessage').html(msg);
}
$(document).ready(function(){
unchk();
var unto;
});
When I declared the variable unto within untmr() it did not delay the execution of unmsg(), and when I changed it to global, it stopped executing altogether. Hmmm.

Before you can assign to unto, you need to declare it.
var unto;
function untmr(msg){
clearTimeout(unto);
unto = setTimeout(unmsg(msg),1500);
}
and since you're calling unmsg, it will need to return a function that gets passed to setTimeout...
function unmsg(msg){
return function() { $('#uNMessage').html(msg); }
}

try:
function untmr(msg){
clearTimeout(unto);
unto = setTimeout(function(){unmsg(msg);} ,1500);
}

Related

Check if password is correct jquery

I have problem with a log in form. When I try to log in the javascript always returns the false value even when I am typing correct username and password.
Here is my code in the jQuery file:
$(document).ready(function(){
var teamname = $("#teamname");
var teampassword = $("#teampassword");
function isPasswordCorrect()
{
var password = teampassword.val();
var name = teamname.val();
var result = false;
$.post('../php/validations/validatePassword.php', {tname: name, tpassword: password}, function(data){
if(data == 1){
result = true;
}else{
result = false;
}
});
return result;
}
$("#join").click(function(){
if(isPasswordCorrect()){
alert("You have joined");
}else{
alert("You have not joined");
}
});
});
Here is my code in the PHPfile:
<?php
$teamname = $_POST['tname'];
$teampassword = $_POST['tpassword'];
if($teamname != "" || $teampassword !=""){
include('../connection.php'); // Here is the log in to the phpmyadmin
$queryCheckPassword = mysqli_query($con, "SELECT password FROM
teams WHERE name = '$teamname'");
$row = mysqli_fetch_row($queryCheckPassword);
$teamPassword = $row[0];
if($teamPassword == $teampassword)
{
echo 1;
}else{
echo 0;
}
}
?>
And here is my code in HTML file:
<form id="joinform"> <!-- action="teams.php" method="post"> -->
<ul>
<div>
<label>Team name&nbsp<font color='red'>*</font></label>
<input type='team' name='teamname' id='teamname' placeholder='Team name' readonly='readonly'/>
<span id='teamnameinfo'>Select an existing team</span>
</div>
<div>
<label for="teampassword">Team password&nbsp<font color='red'>*</font></label>
<input type='password' name='teampassword' id="teampassword" placeholder='Team password'/>
<span id='teampasswordinfo'>Write team password</span>
</div>
<div>
<button name='join' id='join'>Join</button>
</div>
</ul>
</form>
The problem lies in your use of Javascript. Look at your isPasswordCorrect function (which I have reformatted slightly to make the issue a little clearer):
function isPasswordCorrect()
{
var password = teampassword.val();
var name = teamname.val();
var result = false;
$.post(
'../php/validations/validatePassword.php',
{tname: name, tpassword: password},
function (data) {
if(data == 1){
result = true;
}else{
result = false;
}
}
);
return result;
}
See that function (data) {} in there? That's a callback. The way the $.post method works is this:
your JS code sends a request to the server using $.post
your JS code continues, moving on to whatever comes next
Some time later (could be 10 milliseconds later, could be 30 seconds later), the server responds to the request. At that point your callback is called.
What does this mean? When your code hits the return result; line, your code has just submitted the request to the server and the server has probably not responded yet. Thus, result is still false.
A quick solution to this problem is to move the alert statements into the callback, like this:
function isPasswordCorrect()
{
var password = teampassword.val();
var name = teamname.val();
$.post(
'../php/validations/validatePassword.php',
{tname: name, tpassword: password},
function (data) {
if(data == 1){
alert("You have joined");
}else{
alert("You have not joined");
}
}
);
}
$("#join").click(function(){ isPasswordCorrect(); });
However, I imagine you're going to want to do more than just alert something. You're going to need to research the asynchronous nature of Javascript and understand it before you can extend this fragment to do much.
PeterKA is correct about the async. The default value (false) is probably be returning before your async call comes back. Try adding a callback instead (untested):
function isPasswordCorrect(callback)
{
var password = teampassword.val();
var name = teamname.val();
$.post('../php/validations/validatePassword.php', {tname: name, tpassword: password},
function(data) { callback(data == 1); });
}
$("#join").click(function(){
isPasswordCorrect(function(result) {
if (result)
alert("You have joined");
else
alert("You have not joined");
});
});
Because AJAX does not return the result immediately - ASYNCHRONOUS - you want to do the check only and only when you have the result - in the AJAX callback like so:
function isPasswordCorrect()
{
var password = teampassword.val();
var name = teamname.val();
$.post(
'../php/validations/validatePassword.php',
{ tname: name, tpassword: password },
function(data) {
if(data == 1) {
alert("You have joined");
} else {
alert("You have not joined");
}
}
);
}
$("#join").click(isPasswordCorrect);

Form submission according to ajax condition is not working

I have a form submission page, call a function at the time of form submission.Include an ajax.Form submission occur or not according to the condition in ajax.Ajax msg have two values 1 and 0,one value at a time.My requirement is when msg==1 form not submit and msg==0 submit form.But now in both cases form is not submitting.
My code is given below.Anybody give any solution?
main page
<form action="addCustomer_basic.php" method="post"
name="adFrm" id="myform" >
<input name="name" type="text"
class="txtfld" id="name"
value=">" style="width:250px;"/>
<input name="email" type="text"
class="txtfld" id="email" value="" style="width:250px;"/>
<input name="submit" type="submit" value="Submit" />
</form>
<script language="JavaScript">
$(function() {
$("#myform").submit(function(e) {
var $form = $(this);
var cust_name = $form.find('[name="name"]').val();
e.preventDefault();// prevent submission
var email = $form.find('[name="email"]').val();
$.ajax({
type: "POST",
url: 'ajx_customer_mailid.php',
data:'cust_name='+cust_name + '&email=' + email,
success: function(msg)
{
alert(msg);
if(msg==1)
{
alert("Email Id already excist in database");
return false;
}
else
{
self.submit();
}
}
});
});
});
</script>
ajx_customer_mailid.php
<?php
require_once("codelibrary/inc/variables.php");
require_once("codelibrary/inc/functions.php");
$cust_id=$_POST['cust_name'];
$email=$_POST['email'];
$se="select * from customer where name='$cust_id' and email='$email'";
$se2=mysql_query($se);
if($num>0)
{
echo $status=1;
}
else
{
echo $status=0;
}
?>
I've checeked your code, without ajax, and just set directly the msg to 1 or to 2.
See my code, now you can simulate it:
$("#myform").submit(function(e) {
var $form = $(this);
e.preventDefault();// prevent submission
var msg = 2;
if (msg === 1) {
alert("Email Id already excist in database");
return false;
} else {
$form.submit(); //This causes Too much recursion
}
});
There are some errors in it.
So, self.submit(); is bad:
TypeError: self.submit is not a function
self.submit();
You need to rewrite it to $form.submit();
But in that case, if the form needs to submit, you will get an error in your console:
too much recursion
This is because, if it success, then it fires the submit again. But, because in the previous case it was succes, it will be success again, what is fires the submit again, and so on.
UPDATE:
Let's make it more clear what happens here. When you submit the form, after you call e.preventDefault() what prevents the form to submit. When ajax need to submit the form, it triggers the submit(), but you prevent it to submit, but ajax condition will true again, so you submit again, and prevent, and this is an inifinte loop, what causes the too much recursion.
NOTE:
if($num>0) Where the $num is come from? There are no $num anywhere in your php file. You also do not fetch your row of your sql query.
Use mysqli_* or PDO functions instead mysql_* since they are deprecated.
Avoid sql injection by escaping your variables.
So you need to use like this:
$se = "select * from customer where name='$cust_id' and email='$email'";
$se2 = mysql_query($se);
$num = mysql_num_rows($se2); //NEED THIS!
if ($num > 0) {
echo $status = 1;
} else {
echo $status = 0;
}
But i am suggest to use this:
$se = "SELECT COUNT(*) AS cnt FROM customer WHERE name='".mysql_real_escape_string($cust_id)."' and email='".mysql_real_escape($email)."'";
$se2 = mysql_query($se);
$row = mysql_fetch_assoc($se2); //NEED THIS!
if ($row["cnt"] > 0) {
echo $status = 1;
} else {
echo $status = 0;
}
By the time your ajax call finishes, submit handler already finished so the submit continues, it's async you know, so the function makes the ajax call and continues executing. You can do something like this http://jsfiddle.net/x7r5jtmx/1/ What the code does is it makes the ajax call, then waits until the ajax success updates the value of a variable, when the value is updated, if the value is 1, no need to do anything, as we already stopped the form from submittin. If the value is 0, then trigger a click on the button to re-submit the form. You can't call submit inside the submit handler, but you can trigger click on the button. You obviously need to change the ajax call, just set msg inside your success.
var data = {
json: JSON.stringify({
msg: 0 //change to 1 to not submit the form
}),
delay: 1
}
var msg = null;
var echo = function() {
return $.ajax({
type: "POST",
url: "/echo/json/",
data: data,
cache: false,
success: function(json){
msg = json.msg;
}
});
};
$( "#myform" ).submit(function( event ) {
echo();
var inter = setInterval(function(){
console.log("waiting: " + msg);
if (msg != null){
clearInterval(inter);
}
if (msg == 0){
$( "#myform" ).off(); //unbind submit handler to avoid recursion
$( "#btnn" ).trigger("click"); //submit form
}
}, 200);
return false; //always return false, we'll submit inside the interval
});

.click() jquery function not working

I have wrote this code in php:
public function getinfo($username){
$this->autoRender = false;
if($this->request->is('ajax')){
if(!ereg('^[A-Za-z0-9_.]+$',$username)){
echo 'username';
}
else{
$user = $this->User->find('all',array('conditions'=>array('User.username'=>$username)));
if(empty($user)){
echo 'Fail';
}
else{
$this->loadModel('Question');
$question = $this->Question->find('all',array('conditions'=>array('Question.id'=>$user[0]['User']['questionid'])));
echo 'Sec Question : ' . $question[0]['Question']['title'] . '<br />';
echo 'Answer: <input type="text" id="userAnswer" class="loginField" name="data[answer]" /> ';
echo '<input type="submit" id="sendAnswer" class="button" value="send" /> <br />';
echo '<span id="recoverErr"></span>';
$this->Session->write('recoverPass',$user[0]);
}
}
}
else{
$this->redirect(array('controller'=>'message','action'=>'forbidden'));
}
}
And I have wrote this in my jquery file:
$('#send').click(function(){
var recover = $('#recoverUsername').val();
$('#recErr').css('color', 'red');
if(recover == ''){
$('#recoverUsername').focus();
$('#recErr').html('Enter username');
return false;
}
$.ajax({
url: $('#base').html() + '/users/getinfo/'+recover,
type: 'POST',
success: function(data){
if(data.match('username')){
$('#recErr').html('Enter correct username.');
}
else if(data.match('Fail')){
$('#recErr').html("This username doesn't exist");
}
else{
$('#recErr').html('');
$('#recoverWindow').html(data);
$('#recoverWindow').dialog('open');
}
}
});
});
$('#sendAnswer').click(function(){
var answer = $('#userAnswer').val();
$.ajax({
url: $('#base').html() + '/users/getanswer/'+answer,
type: 'POST',
success: function(data){
if(data.match('answer')){
$('#recoverErr').html('Enter answer');
}
else if(data.match('Fail')){
$('#recoverErr').html('answer is false.');
}
else if(data.match('Bad')){
$('#recoverErr').html('fail too send mail.');
}
else{
$('#recoverWindow').html('');
$('#recoverWindow').html('Email was sent, check your spam if it is not in your inbox.');
}
}
});});
but when I click and the server found the User's info and put it in recoverWindow the click function doesn't work and doesn't send the answer to the action.
please Help me, i don't have time
You have used Ajax for creating recover form in your php function. so you can't put $('#sendAnswer').click() in ready function. Because sendAnswer element doesn't exist in your HTML and you want create in your php file.
So you should write click function for this element after ajax execution. With this explanation your JQuery Code should change to this:
$('#send').click(function(){
var recover = $('#recoverUsername').val();
$('#recErr').css('color', 'red');
if(recover == ''){
$('#recoverUsername').focus();
$('#recErr').html('Enter username');
return false;
}
$.ajax({
url: $('#base').html() + '/users/getinfo/'+recover,
type: 'POST',
success: function(data){
if(data.match('username')){
$('#recErr').html('Enter correct username.');
}
else if(data.match('Fail')){
$('#recErr').html("This username doesn't exist");
}
else{
$('#recErr').html('');
$('#recoverWindow').html(data);
$('#recoverWindow').dialog('open');
$('#sendAnswer').click(function(){
var answer = $('#userAnswer').val();
$.ajax({
url: $('#base').html() + '/users/getanswer/'+answer,
type: 'POST',
success: function(data){
if(data.match('answer')){
$('#recoverErr').html('Enter answer');
}
else if(data.match('Fail')){
$('#recoverErr').html('answer is false.');
}
else if(data.match('Bad')){
$('#recoverErr').html('fail too send mail.');
}
else{
$('#recoverWindow').html('');
$('#recoverWindow').html('Email was sent, check your spam if it is not in your inbox.');
}
}
});});
}
}
});});
Help me, i don't have time
thats the reason you didn't search for other related answer..
anyways like many other answers in stackoverflow including mine , here i go again..
you need to delegate click event for dynamically added element using on
$('#recoverWindow').on('click','#sendAnswer',function(){
....
instead of
$('#sendAnswer').click(function(){
If your element with id="sendAnswer" is loading via ajax and you wrote click event for that in your main page then you have to use .on() or .live() method to get it executed.
But they both methods are used for different jQuery versions.
Please write it as following
$(document).ready(function() {
//if you are using jQuery version after 1.7 then use following
$(document).on('click', '#sendAnswer', function(){
//your logic
});
//if you are using jQuery version upto 1.7 then use following
$('#sendAnswer').live('click', function(){
//your logic
});
});

jQuery Post and Get Form data

When a form is submitted, I can get its field values with $_POST. However, I am trying to use a basic jQuery (without any plugin) to check if any field was blank, I want to post the form content only if theres no any blank field.
I am trying following code, and I got the success with jQuery, but the only problem is that I am unable to post the form after checking with jQuery. It does not get to the $_POST after the jQuery.
Also, how can I get the server response back in the jQuery (to check if there was any server error or not).
Here's what I'm trying:
HTML:
<form action="" id="basicform" method="post">
<p><label>Name</label><input type="text" name="name" /></p>
<p><label>Email</label><input type="text" name="email" /></p>
<input type="submit" name="submit" value="Submit"/>
</form>
jQuery:
jQuery('form#basicform').submit(function() {
//code
var hasError = false;
if(!hasError) {
var formInput = jQuery(this).serialize();
jQuery.post(jQuery(this).attr('action'),formInput, function(data){
//this does not post data
jQuery('form#basicform').slideUp("fast", function() {
//how to check if there was no server error.
});
});
}
return false;
});
PHP:
if(isset($_POST['submit'])){
$name = trim($_POST['name'];
$email = trim($_POST['email'];
//no any error
return true;
}
To be very specific to the question:
How can I get the server response back in the jQuery (to check if
there was any server error or not). Here's what I'm trying:
Sound like you're talking about Server-Side validation via jQuery-Ajax.
Well, then you need:
Send JavaScript values of the variables to PHP
Check if there any error occurred
Send result back to JavaScript
So you're saying,
However, I am trying to use a basic jQuery (without any plugin) to
check if any field was blank, I want to post the form content only if
there's no any blank field.
JavaScript/jQuery code:
Take a look at this example:
<script>
$(function()) {
$("#submit").click(function() {
$.post('your_php_script.php', {
//JS Var //These are is going to be pushed into $_POST
"name" : $("#your_name_field").val(),
"email" : $("#your_email_f").val()
}, function(respond) {
try {
//If this falls, then respond isn't JSON
var result = JSON.parse(respond);
if ( result.success ) { alert('No errors. OK') }
} catch(e) {
//So we got simple plain text (or even HTML) from server
//This will be your error "message"
$("#some_div").html(respond);
}
});
});
}
</script>
Well, not it's time to look at php one:
<?php
/**
* Since you're talking about error handling
* we would keep error messages in some array
*/
$errors = array();
function add_error($msg){
//#another readers
//s, please don't tell me that "global" keyword makes code hard to maintain
global $errors;
array_push($errors, $msg);
}
/**
* Show errors if we have any
*
*/
function show_errs(){
global $errors;
if ( !empty($errors) ){
foreach($errors as $error){
print "<p><li>{$error}</li></p>";
}
//indicate that we do have some errors:
return false;
}
//indicate somehow that we don't have errors
return true;
}
function validate_name($name){
if ( empty($name) ){
add_error('Name is empty');
}
//And so on... you can also check the length, regex and so on
return true;
}
//Now we are going to send back to JavaScript via JSON
if ( show_errs() ){
//means no error occured
$respond = array();
$respond['success'] = true;
//Now it's going to evaluate as valid JSON object in javaScript
die( json_encode($respond) );
} //otherwise some errors will be displayed (as html)
You could return something like {"error": "1"} or {"error": "0"} from the server instead (meaning, put something more readable into a JSON response). This makes the check easier since you have something in data.
PHP:
if(isset($_POST['submit'])){
$name = trim($_POST['name'];
$email = trim($_POST['email'];
//no any error
return json_encode(array("error" => 0));
} else {
return json_encode(array("error" => 1));
}
JavaScript:
jQuery('input#frmSubmit').submit(function(e) {
//code
var hasError = false;
if(!hasError) {
var formInput = jQuery(this).serialize();
jQuery.post(jQuery(this).attr('action'),formInput, function(data){
var myData = data;
if(myDate.error == 1) {//or "1"
//do something here
} else {
//do something else here when error = 0
}
});
}
$("form#basicform").submit();
return false;
});
There are two ways of doing that
Way 1:
As per your implementation, you are using input[type="submit"] Its default behavior is to submit the form. So if you want to do your validation prior to form submission, you must preventDefault() its behaviour
jQuery('form#basicform').submit(function(e) {
//code
e.preventDefault();
var hasError = false;
if(!hasError) {
var formInput = jQuery(this).serialize();
jQuery.post(jQuery(this).attr('action'),formInput, function(data){
//this does not post data
jQuery('form#basicform').slideUp("fast", function() {
//how to check if there was no server error.
});
});
}
$(this).submit();
return false;
});
Way 2:
Or simply replace your submit button with simple button, and submit your form manually.
With $("yourFormSelector").submit();
Change your submit button to simple button
i.e
Change
<input type="submit" name="submit" value="Submit"/>
To
<input id="frmSubmit" type="button" name="submit" value="Submit"/>
And your jQuery code will be
jQuery('input#frmSubmit').on('click',function(e) {
//code
var hasError = false;
if(!hasError) {
var formInput = jQuery(this).serialize();
jQuery.post(jQuery(this).attr('action'),formInput, function(data){
//this does not post data
jQuery('form#basicform').slideUp("fast", function() {
//how to check if there was no server error.
});
});
}
$("form#basicform").submit();
return false;
});
To get the response from the server, you have to echo your response.
Suppose, if all the variables are set, then echo 1; else echo 0.
if(isset($_POST['submit'])){
$name = trim($_POST['name'];
$email = trim($_POST['email'];
echo 1;
} else {
echo 0;
}
And in your success callback function of $.post() handle it like
jQuery.post(jQuery(this).attr('action'),formInput, function(data){
//this does not post data
jQuery('form#basicform').slideUp("fast",{err:data}, function(e) {
if(e.data.err==1){
alert("no error");
} else {
alert("error are there");
});
});

real time validation of username and email address using ajax post

I set up a simple form and use ajax+jquery to check for valid username (doesn't exist in DB) and email address (valid format and doesn't exist in DB) as follows
<body>
<div>
<h5> Sign Up </h5>
<hr />
<div>
Username:<input type="text" size="32" name="membername" id="username"><div id="usernameStatus"></div><br />
Email:<input type="text" size="32" name="memberemail" id="memberemail"><div id="emailStatus"></div><br/>
Password:<input type="password" size="32" name="memberpwd"><br />
<button id="signup" disabled="true">Sign Up</button>
</div>
<script>
function IsEmailValidAndNew()
{
var pattern = new RegExp(/^(("[\w-+\s]+")|([\w-+]+(?:\.[\w-+]+)*)|("[\w-+\s]+")([\w-+]+(?:\.[\w-+]+)*))(#((?:[\w-+]+\.)*\w[\w-+]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][\d]\.|1[\d]{2}\.|
[\d]{1,2}\.))((25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\.){2}(25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\]?$)/i);
var success=false;
$("#memberemail").change(function()
{
var email=$("#memberemail").val();
success=patter.test(email);
if(success)
{
$("#usernameStatus").html('<img align="absmiddle" src="loading.gif"/> Checking email...');
$.ajax(
{
type: "POST",
url:"regcheckemail.php",
data:"memberemail="+email,
success: function(msg)
{
$("#emailStatus").ajaxComplete(function(event, request, settings)
{
if(msg=="OK")
{
$("#memberemail").removeClass("object_error");
$("#memberemail").addClass("object_ok");
$(this).html('<img align="absmiddle" src="checkmark.png"/>');
success=true;
}
else
{
$("#memberemail").removeClass('object_ok');
$("#memberemail").addClass("object_error");
$(this).html(msg);
success=false;
}
}
);
}
}
);
}
else
{
$("#emailStatus").html("Provided email address is ill-formed");
$("#memberemail").removeClass('object_ok'); // if necessary
$("#memberemail").addClass("object_error");
success=false;
}
}
);
return success;
}
function IsUserAlreadyExist()
{
var success=false;
$("#username").change(function()
{
var usr=$("#username").val();
if(usr.length>=7)
{
$("#usernameStatus").html('<img align="absmiddle" src="loading.gif"/> Checking availability...');
$.ajax(
{
type: "POST",
url:"regcheckuser.php",
data:"username="+usr,
success: function(msg)
{
$("#usernameStatus").ajaxComplete(function(event, request, settings)
{
if(msg=="OK")
{
$("#username").removeClass("object_error");
$("#username").addClass("object_ok");
$(this).html('<img align="absmiddle" src="checkmark.png"/>');
success=true;
}
else
{
$("#username").removeClass('object_ok');
$("#username").addClass("object_error");
$(this).html(msg);
success=false;
}
}
);
}
}
);
}
else
{
$("#usernameStatus").html("The username should have at least 7 characters");
$("#username").removeClass('object_ok');
$("#username").addClass("object_error");
success=false;
}
});
return success;
}
$(document).ready(function()
{
if(IsEmailValidAndNew() && IsUserAlreadyExist())
{
$('button').find("#signup").attr("disabled","false");
}
else
{
$('button').find("#signup").attr("disabled","true");
}
});
</script>
</div>
</body>
I use notepad to code it, it doesn't work and I can't find out the mistake. I don't know any good tool you might be using to code in javascript that has awesome options like an embedded intellisense and debug capability.
There are several problems with your code.
Your email regex is not thorough enough (OK, this isn't actually stopping the code working, but it's the first thing I noticed).
Your ajax calls are asynchronous, which is good, but means that the functions that do the $.ajax() calls will complete before the ajax response is received. You need to restructure this to do something from the ajax success callback.
You don't need the ajaxComplete() function - you're already within an ajax success handler at that point so put the code within your current ajaxComplete() directly in the containing success function.
You call IsEmailValidAndNew() and IsUserAlreadyExist() once from your document ready and disable or enable the "signup" control, but at no point after that do you re-enable or re-disable it. You are calling these functions as if they will validate the fields, but really what they do is set up change handlers on the fields so the code in the functions won't do anything until the fields actually get changed by the user.
Following is one way you could structure your code instead:
$(document).ready(function() {
var emailOK = false,
nameOK = false;
function setSubmitEnabling() {
$("#signup").prop("disabled", !(emailOK && nameOK));
}
setSubmitEnabling();
$("#username").change(function() {
var usr = $(this).val();
if (usr.length < 7) {
$("#usernameStatus").html("The username should have at least 7 characters");
$(this).removeClass('object_ok').addClass("object_error");
nameOK = false;
setSubmitEnabling();
} else {
// format seems OK, so do ajax call:
$("#usernameStatus").html('<img align="absmiddle" src="loading.gif"/> Checking availability...');
$.ajax({
type: "POST",
url:"regcheckuser.php",
data:"username="+usr,
success : function(msg) {
if(msg === "OK")
{
$("#username").removeClass("object_error")
.addClass("object_ok");
$("#usernameStatus").html('<img align="absmiddle" src="checkmark.png"/>');
nameOK = true;
}
else
{
$("#username").removeClass('object_ok')
.addClass("object_error");
$("#usernameStatus").html(msg);
nameOK = false;
}
// now update button state
setSubmitEnabling();
}
});
}
});
$("#memberemail").change(function() {
// basically the same thing as for the username field as shown above,
// except setting emailOK instead of nameOK, so I suggest you get the
// username part working first then come back to do this the same way
});
});
The idea of the above code is that there are several points where you need to enable or disable the "signup" button, and that depends on two unrelated conditions. So create a flag for each of those conditions, and function setSubmitEnabling() that checks the flags and enables or disables the buttons. Call that function immediately when the page loads to set the initial enable/disable state, and call it again any time something changes that needs the enable/disable state to be re-evaluated.
Also, create a change handler for each of your two fields. The change handlers will be similar to each other, basically doing some initial quick validation to see if the length and format is OK and if so an ajax call to test for uniqueness.

Categories