In this case, you can use callbacks . Just separate the code as shown below:
with a callback that will return the 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?'}); } } }); }
This returns the result of an AJAX call. It will wait for AJAX to complete and return the corresponding branch result if ...
.. and now you can use it like 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 connect them like this:
$('#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
source share