0

this is my code here if(flag=="no") not working, the flag value is not changing, always it prevent default. is there any mistake in my code. ajax return are correct.

$(document).ready(function() {
    $('#submit').click(function(event) {
        var captcha = $("#captcha").val();
        var flag = "no";
        if (captcha == '') {
            alert("Fill Captcha Field");
            event.preventDefault();
        } else {
            var dataString = captcha;
            $.ajax({
                type: "POST",
                url: "verify.php",
                data: {
                    code: captcha
                },
                success: function(data) {
                    if (data == "no") {
                        alert("Invalid Captcha");
                    } else {
                        flag = "yes";
                    }
                }
            });
        }
        if (flag == "no") {
            return false;
        } else {
            return true;
        }
    });
});
Jenish Rabadiya
  • 6,708
  • 6
  • 33
  • 62
Asif
  • 65
  • 8

2 Answers2

0

You can try this one, its working example.

var jqXHR = $.ajax({
        url: "verify.php",
        type: "POST",
        data: {code: captcha},
        async: false,
        success: function (data) {
        }
    });

if(jqXHR.responseText=="no")
 {
 alert("Invalid Captcha");                                              
 }
 else
 {
 flag="yes";
 }

if(flag=="no")
 {
 return false;
 }
 else{
 return true;
 }

It will return after the successfully returning data from ajax request

Umesh Sehta
  • 10,555
  • 5
  • 39
  • 68
0

By default javascript requests are sent asynchronously. when ajax is call take time to get response javascript execute next code. here in your code it is same issue. use below code

$(document).ready(function() {

  $('#submit').click(function(event) {
    var captcha = $("#captcha").val();
    var response ;
    if (captcha == '') {
        alert("Fill Captcha Field");
        event.preventDefault();
    } else {
      var dataString = captcha;
      response = $.ajax({
            type: "POST",
            url: "verify.php",
            data: {
                code: captcha
            },
            success: function(data) {

            }
        }).responseText;
    }

     if (response == "no") {
           alert("Invalid Captcha");
           return false;
      } else {
           return true;
      }
 });
});
Nishit Maheta
  • 6,021
  • 3
  • 17
  • 32