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.
Related
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 <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 <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);
I have a simple form that can display 2 error codes at once, but I need only one to display (see below). #1 should be the only one displayed if user enters an invalid email , invalidity is determined by the form input text required pattern=.... Error #2 should be the only visible error if the email is valid. It is produced from a PHP result - this PHP file is called on via ajax within the form's html file and returns a result which is displayed as error #2.
My question: how do I apply an IF statement or similar, to determine whether
the form's input field's pattern is satisfied or not. If it is unsatisfied (invalid) then perhaps we could make it's font-size 0px by altering it's CSS somehow, which would make only #2 visible. If it is satisfied, then we could continue to hide error #2's div somehow.
Here is the form (with error #2's hidden div "formResponse"):
<form id="loginform" name="loginform" method="POST" class="login" action="#">
<input name="emailaddy" id="emailaddy" type="email" class="feedback-input" placeholder="My Email" required pattern="[a-z0-9!#$%&'*+/=?^_`{|}~)" required title="Invalid Email"/>
<div id="formResponse" style="display: none;"></div>
<button type="submit" name="loginsubmit" class="loginbutton">Login</button>
</form>
and the css:
div.error, div.error-list, label.error, input.error, select.error, textarea.error {
color: #D95C5C!important;
border-color: #D95C5C!important;
font-size: 18px;
}
Updated AJAX (via reggie's answer) - NOTE: I don't think if(ema == null || ema == '') is working, because even if the user enters gibberish it still displays both errors. But if I change it to if(ema == 'a'), it properly hides formResponse div and only shows label.error. I need it to hide formResponse if the field is invalid/null - but null doesn't seem to work. Also, the else function doesn't work, meaning the label.error div won't hide for some reason. Perhaps null should be replaced with a regular expression check?
UPDATED AJAX: Why is it treating "hello#example.com" as null?
<script>
$(document).ready(function() {
$("#loginform").submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "login/login.php",
dataType:"text",
data: {email: $('#emailaddy').val(), loginsubmit: 'yes'},
success:function(result){
if(result === "redirect"){
window.location.replace("http://www.example.com/login/private.php");
}
else{
//var re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\#[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
var email = $('#emailaddy').val();
var pattern = ".+\\##.+\\..+";
var valid = email.match(pattern);
alert(valid);
if (valid == null) {
}
else {
$("#formResponse").html("That email address is not registered.").show();
}
}
}
})
});
});
</script>
In ajax, you could check the email and stop it from going to the server if invalid:
var ema = $('#useremail').val();
if(ema == null || ema == '' //or whatever)
{
$('.error1').show();
$('.error1').html('Nope');
$('.error2').hide();
return;
}
else{
//continue with ajax
Then handle any errors coming back from php like:
success: function(responseText) {
if(responseText == "1") {
$('.error1').hide();
$('.error2').show();
$('.error2').html(//the error msg);
}
YOU CAN USE INVALID PSEUDO CLASS :
input[type=email]:invalid {
color: red;
}
here is a bunch a css validation pseudo class you can use :
input:valid { ... }
input:invalid { ... }
input:required,
input[aria-required="true"] { ... }
input:optional { ... }
input:out-of-range { ... }
input:in-range { ... }
Here is an exmple I made it for you, try to type an invalid email and you'll see the magic :
Live Demo
I seem to have solved my problem by following reggie's lead, and adapting it to fit my code as such:
<script>
$(document).ready(function() {
$("#loginform").submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "login/login.php",
dataType:"text",
data: {email: $('#emailaddy').val(), loginsubmit: 'yes'},
success:function(result){
if(result === "redirect"){
window.location.replace("http://www.example.com/login/private.php");
}
else{
//var re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\#[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
var email = $('#emailaddy').val();
if(email.match(/^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/)) {
$("#formResponse").html("That email address is not registered.").show();
}
else {
}
}
}
})
});
});
</script>
It only shows error #2 (formResponse) if the email is valid but not registered.
I'm totally new to jquery and AJAX, After trying hard for 5-6 hours and searching the solution I'm asking for the help.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".submit").live('click',(function() {
var data = $("this").serialize();
var arr = $("input[name='productinfo[]']:checked").map(function() {
return this.value;
}).get();
if(arr=='')
{
$('.success').hide();
$('.error').show();
}
else
{
$.ajax({
data: $.post('install_product.php', {productvars: arr}),
type: "POST",
success: function(){
$(".productinfo").attr('checked', false);
$('.success').show();
$('.error').hide();
}
});
}
return false;
}));
});
</script>
and HTML+PHP code is,
$json = file_get_contents(feed address);
$products = json_decode($json);
foreach(products as product){
// define various $productvars as a string
<input type="checkbox" class="productvars" name="productinfo[]" value="<?php echo $productvars; ?>" />
}
<input type="submit" class="submit" value="Install Product" />
<span class="error" style="display:none"><font color="red">No product selected.</font></span>
<span class="success" style="display:none"><font color="green">product successfully added to database.</font></span>
As I'm pulling the product information from feed, I don't want to refresh the page, that's why I'm using AJAX post method. Using above code "install_product.php" page is handling the string properly and doing its job properly.
The problem I'm facing is, when first time I check the check box and install the product it works absolutely fine, but after first post "Sometimes it work and sometimes it won't work". As new list is pulled from feed every first post is perfect after that I need to click install button again and again to do so.
I tested the code on different browsers, but same problem. What may be the problem?
(I'm testing the code on live host not localhost)
$.live is deprecated, consider using $.on() instead.
Which function is not executing after it executes once? $.live?
Also, it should be:
var data = $(this).serialize();
not
var data = $("this").serialize();
In your example, you are looking for an explicit tag called 'this', not a scope.
UPDATE
$(function () {
$(".submit")
.live('click', function(event) {
var data = $(this).serialize();
var arr = $("input[name='productinfo[]']:checked")
.map(function () {
return this.value;
})
.get();
if (arr == '') {
$('.success')
.hide();
$('.error')
.show();
} else {
$.ajax({
data: $.post('install_product.php', {
productvars: arr
}),
type: "POST",
success: function () {
$(".productinfo")
.attr('checked', false);
$('.success')
.show();
$('.error')
.hide();
}
});
}
event.preventDefault();
});
});
Is it possible, it is missing the value at arr and showing up the error or is it like it is making call but not returning or it is not reaching the call at all?
Do a console.log to deal with debuging and check things out in firefox / chrome and see what and where is the issue.
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");
});
});
i just pluged a JQuery username check which worked fine , the problem is that my form still submitting even the username exist on my Mysq Database, how can i configure it to deny submitting to my server side .php file if it exists ?
here is my Jquery plugin javascript code
$(document).ready(function() {
//the min chars for checkusername
var min_chars = 3;
//result texts
var characters_error = 'Minimum amount of chars is 3';
var checking_html = '<img src="images/checkusername.gif" /> Checking...';
//when button is clicked
$('#check_checkusername_availability').click(function(){
//run the character number check
if($('#checkusername').val().length < min_chars){
//if it's bellow the minimum show characters_error text
$('#checkusername_availability_result').html(characters_error);
}else{
//else show the cheking_text and run the function to check
$('#checkusername_availability_result').html(checking_html);
check_availability();
}
});
});
//function to check checkusername availability
function check_availability(){
//get the checkusername
var checkusername = $('#checkusername').val();
//use ajax to run the check
$.post("frontend/functions/f_checkuser.php", { checkusername: checkusername },
function(result){
//if the result is 1
if(result == 1){
//show that the checkusername is available
$('#checkusername_availability_result').html('<span class="is_available"><b>' +checkusername + '</b> is Available</span>');
}else{
//show that the checkusername is NOT available
$('#checkusername_availability_result').html('<span class="is_not_available"><b>' +checkusername + '</b> is not Available</span>');
}
});
}
here is my html field
<table border="0" >
<tr>
<td valign="middle"><input class="input_field_12em required userUserName" name="userUserName" id="checkusername"></td>
<td valign="middle"><input type='button' id='check_checkusername_availability' value='Check Availability'></td>
<td><div id='checkusername_availability_result'></div></td>
</tr>
</table>
You can wait for the callback to fire for your AJAX request, then you can either submit the form or not:
$(function () {
$('form').on('submit', function (event, extra) {
if (typeof extra == 'undefined') {
extra = false;
}
//if no extra argument is passed via `.trigger()` then don't submit the form
return extra;
});
$('#check_checkusername_availability').on('click', function () {
$.ajax({
url : 'frontend/functions/f_checkuser.php',
type : 'post',
data : { checkusername : $('#checkusername').val() },
success : function (serverResponse) {
//now check the serverResponse variable to see if the name exists, if not then run this code:
$('form').trigger('submit', true);
},
error : function (jqXHR, textStatus, errorThrown) { /*don't forget to handle possible errors*/ }
});
});
});
Otherwise, you can force the AJAX request to be synchronous by setting async:false, but this will lock-up the browser until the AJAX request resolves, which could be seconds where the user can't do anything. This gives the impression that your script is broken to the user.
You didn't post your html but it seems like clicking on object with id check_checkusername_availability triggers form submit in some way. Is it a submit button? If that's the case just change it to the regular button. And add callback to handle the resonse.