I\'m validating for duplicate names by using jquery+Ajax. Everything is working fine except that the form is not submitting once everything returns true
What
You can benefit from the callbacks
in this case. Just separate the code like below:
function with the callback that will return an object {status: 'true or false', message: 'Some text'}
function validity(callback){
var name = $('#shelf_name').val();
if(name == '')
{
return callback({status: false, message: 'Shelf name is required'});
}
else
{
$.ajax({
type:'post',
url:'check-duplicate-shelf-name.php',
data:{'name':name},
context:this,
success:function(data)
{
if(data == 'stop')
{
return callback({status: false, message: 'Shelf name already exists'});
}
else
{
return callback({status: true, message: 'else working?'});
}
}
});
}
//just for safety :))
return callback({status: false, message: 'something went wrong completely'});
});
This returns the result from the AJAX call. It will wait for AJAX to complete and return the corresponding branch result of if
...
.. and you can now use it as this:
$('#form1').submit(function(){
validity(function(result){
if (result.status) { //status is true
return true;
}
else
{
alert(result.message);
$('#shelf_name').focus();
return false;
}
});
});
... or just combine them like :
$('#form1').submit(function(){
// definition
function validity(callback){
var name = $('#shelf_name').val();
if(name == '')
{
return callback({status: false, message: 'Shelf name is required'});
}
else
{
$.ajax({
type:'post',
url:'check-duplicate-shelf-name.php',
data:{'name':name},
context:this,
success:function(data)
{
if(data == 'stop')
{
return callback({status: false, message: 'Shelf name already exists'});
}
else
{
return callback({status: true, message: 'else working?'});
}
}
});
}
//just for safety :))
return callback({status: false, message: 'something went wrong completely'});
});
//usage
validity(function(result){
if (result.status) { //status is true
return true;
}
else
{
alert(result.message);
$('#shelf_name').focus();
return false;
}
});
});
Hope this helps