coolshox coolshox - 2 months ago 5
Javascript Question

how to pass value to function with ajax

I would like to get ajax return value. please help my code does not return value false or true.

I have two functions in this script validate() which calling validateDate() which ajax is present

<script type="text/javascript">
$(document).ready(function(){

function validateDate(date) {

return $.ajax({
type: "POST",
url: "<?php echo base_url(); ?>activate/checkdate",
data: "Date_of_Birth="+date,
success: function(msg){
if(msg=="false"){
return false;
}
else{
return false;
}
}
});
}

function validatesa() {
var date = $("#Datepicker").val();
if (validateDate(date)) {
return true;
} else {
sweetAlert( date , "is not a valid date YYYY-MM-DD", "error");
return false;
}
}
}else {
sweetAlert( date , "is not a valid date YYYY-MM-DD", "error");
return false;
}
}
$("form").bind("submit", validatesa);

});

</script>

Answer

AJAX is asynchronous process so return not allowed. In your case you have to use async : false in your ajax request option. ad have to use return variable. So your function code should be.

function validateDate(date) {
    var response=true;
    $.ajax({
        type: "POST",
        url: "<?php echo base_url(); ?>activate/checkdate",
        async: false,
        data: {
            Date_of_Birth:  date
        },
        success: function(msg) {
            if (msg == "false") {
                response false;
            } else {
                response true;
            }
        }
    });
    return response;
}
Comments