Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return statement executes before ajax response

I am making an ajax call on submit button click event to check field validations server side. When I get a validation fail, ajax response gives the proper error message, returns false, and stops the form to submit to the action url. But when I get a response of 'success', the form is still not submitting to the action url script.

Is this the case when return statement executes before ajax response?

And also why is the form not getting submitted?

Here is the code:

<input type="submit" onclick="return validate();" name="submit" value="Proceed" />

<script type="text/javascript">
    var flag=false;
    function validate(){

        $.ajax({
            type:"POST",
            url:"../chk.php",
            data:datastring,
            cache: false,
            success: function (result) {


                if(result.toString() == "success" ){

                    flag=true;

                }

                else{
                    $('#error').css('display', 'block');
                    $('#error').css('color','red');
                    $('#error').text(result.toString());
                    flag=false;
                }
            }

        });


        return flag;
    }
</script>
like image 295
Nirali Joshi Avatar asked Sep 11 '25 19:09

Nirali Joshi


1 Answers

one Way is

use async : false

Setting async to false means that the statement you are calling has to complete before the next statement in your function can be called.

$.ajax({
            type:"POST",
            url:"../chk.php",
            data:datastring,
            cache: false,
            async : false,
            success: function (result) {

And also why are you returning the value outside the ajax function , return the value inside ajax success if you are not using async : false

 $.ajax({
            type:"POST",
            url:"../chk.php",
            data:datastring,
            cache: false,
            success: function (result) {


                if(result.toString() == "success" ){

                    flag=true;

                }

                else{
                    $('#error').css('display', 'block');
                    $('#error').css('color','red');
                    $('#error').text(result.toString());
                    flag=false;
                }
            }

             return flag;

        });
like image 156
Kanishka Panamaldeniya Avatar answered Sep 13 '25 09:09

Kanishka Panamaldeniya