Reputation: 119
Here is my snippet jquery code. Pratically i would check if field are empty on submit form, then if the username exist show confirm dialog.
<script type="text/javascript">
jQuery(function(){
$("#form").submit(function(){
var isFormValid = true;
if ($.trim($("#telephone").val()).length == 0){
isFormValid = false;
alert("Empty telephone!");
}
elseif(check_field() == 1){
if(confirm('Delete?')){
isFormValid = true;
}else{
isFormValid = false;
}
return isFormValid;
});
function check_field(){
var field = $('#field').val();
$.post("check_field.php", { field: field }, function(result){
//if the result is 1
if(result == 1){
return 1;
}else{
return 0;
}
});
}
});
</script>
Upvotes: 0
Views: 181
Reputation: 27770
Your $.post
call is asynchronous - so the inner return statements don't actually return from inside the check_field
function at all. The inner function is called once the server has responded.
Essentially, the original check_field
function issues the POST request, then continues right on without waiting for the server to respond, returning the control flow to the original submit handler.
What you need to do instead, is wait for the async response from the POST, then trigger the submit if the returned validation succeeded.
A very simply implementation could look something like this:
jQuery(function(){
$("#form").on('submit', function(ev){
ev.preventDefault();
var $form = $(this),
field = $('#field').val();
$.post("check_field.php", { field: field }, function(result){
if (result==1 && confirm('Delete?'))
$form.off().submit();
});
});
});
Note: I updated the code - it is now triggered on the submit
event, so it will work for both clicking the submit button and using the enter
key.
Upvotes: 1
Reputation: 108500
A classic mistake, you need to make a callback in the ajax function because when the function has been executed, the ajax post has not yet been made:
function check_field(callback){
var field = $('#field').val();
$.post("check_field.php", { field: field }, function(result){
//if the result is true
callback(result == 1);
});
}
And then something like:
$("#form").submit(function(e){
e.preventDefault() // prevent the form from submitting... yet
var $form = $(this);
check_field(function(result) {
if(result && confirm('Delete?')) {
$form.submit(); // now submit it
}
});
});
Welcome to the world of asynchronous programming!
Upvotes: 1
Reputation: 3528
You should care about the datatypes. 1 is not equal to "1" or '1'. Is it?! Use "typeof"
to find out the datatype of values. Also just by returning value you can not continue the process. It's a asynchronous call. You should read about that.
Cheers
Upvotes: 0