Search code examples
javascriptjquerypreventdefault

jQuery prevent submit of form inside of if statement


Sorry if there are some mistakes, but I am a total noob and I am also posting for the first time on StackOverflow.

I am trying to configure a submit form, that controls if the inserted PIN is right, and if so goes on with the submission. I did some online research and found out that with jQuery we can use to function event.preventDefault(), I tried to insert it inside my AJAX request but it looks like it doesn't stop the form from being saved.

The code looks like these:

function verifyOTP() {
    $(".error").html("").hide();
    $(".success").html("").hide();
    var otp = $("#contomovimentato").val();
    var PIN =  $("#PINvalue").val();
    var input = {
        "otp" : otp,
        "PIN" : PIN,
        "action" : "verify_otp"
    };
    if (otp != null) {
        $.ajax({
            url : 'm_ajaxpinr.php',
            type : 'GET',
            dataType : "json",
            data : input,
            success : function(response) {
                $("." + response.type).html(response.message)
                $("." + response.type).show();
                },
            error : function() {
                alert("ss");
            }
        });
    } else {
        $(".error").html('XPIN non valido.')
        $(".error").show();
        error : function(event) { event.preventDefault(); };
    }
 //if I insert "return false;" here the submit is always blocked
}

I checked on atom if the parenthesis are right and it looks like it is. Any ideas how I should use the preventDefault()? I also checked if the output of m_ajaxpinr.php is correct, and it is. I also tried like these but it still didn't work...

    if (otp != null) {
        $.ajax({
            url : 'm_ajaxpinr.php',
            type : 'GET',
            dataType : "json",
            data : input,
            success : function(response) {
                $("." + response.type).html(response.message)
                $("." + response.type).show();
        $("form").submit(function(event) {
                    if (response.type == 'success')
                {
                    alert(response.type);
                }
                else if (response.type == 'error') 
                {
                    alert(response.type);
                    event.preventDefault();
                }
                });

Solution

  • as said in comment above ajax call is asynchronous, you need to complete cancel default action for the form or put event.preventDefault(); on the top function, then submit it in success function if it valid otp.

    .val() will not return null, it return empty if no input.

    $('#myForm').on('submit', verifyOTP);
    
    function verifyOTP(e) {
      e.preventDefault(); // note this
      
      $(".error").html("").hide();
      $(".success").html("").hide();
      var otp = $("#contomovimentato").val();
      var PIN = $("#PINvalue").val();
      var input = {
        "otp": otp,
        "PIN": PIN,
        "action": "verify_otp"
      };
    
      if (otp) { // mean not null, undefined, empty, false, 0
        $.ajax({
          //url: 'm_ajaxpinr.php',
          url: 'https://httpbin.org/anything/test',
          type: 'GET',
          dataType: "json",
          data: input,
          success: function(response) {
            $("." + response.type).html(response.message)
            $("." + response.type).show();
            if(response.args.otp == 1234){
               console.log('valid otp, continue submission')
               $('#myForm').off('submit'); // remove submit event
               $('#myForm').submit(); // then submit the form
            }
            else{
              console.log('invalid pin,\nvalid pin: 1234');
            }
          },
          error: function() {
            console.log("server error, submission cancelled");
          }
        });
      } else {
        $(".error").html('XPIN non valido.')
        $(".error").show();
        console.log("otp maybe empty, submission cancelled");
      }
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <form id="myForm">
      <input id="contomovimentato">
      <button>submit</button>
    </form>