简体   繁体   中英

event.preventDefault(); not working in ajax

I am firing an ajax call on a signup form wherein i am checking whether the email id entered by the user has already been used or not. Ajax Function :

<script>


$( "#becomesignup" ).submit(function( event ) {
        $.ajax({
            url : 'login', // Your Servlet mapping or JSP(not suggested)
            data : {"email":$("#becomeemail").val()},
            type : 'GET',
            dataType : 'html', // Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
            success : function(response) {
                if(response == "true"){
                    $('#emailerrorbecome').slideDown();
                    $('#become-submit').prop('disabled', true);
                  event.preventDefault();
                }else{
                    $('#emailerrorbecome').slideUp();
                    $('#become-submit').prop('disabled', false);
                }
                 $('.black-screen').hide();

              },
              error : function(request, textStatus, errorThrown) {
                alert(errorThrown);

            }
        });
});
</script>

In the above ajax function, if the response is true then the email id is already been used and i need to show an error div($('#emailerrorbecome').slideUp();) and then prevent the form to get submitted. But even event.preventDefault() is not working causing the emaild id to be registered again. Please help me with this. TIA

You should submit the form programatically and always preventing default behaviour in jq submit handler. Eg, using context and calling submit() DOM API method:

$("#becomesignup").submit(function(event) {
    event.preventDefault(); /* prevent form submiting here */
    $.ajax({
        context: this, /* setting context for ajax callbacks*/
        url: 'login', // Your Servlet mapping or JSP(not suggested)
        data: {
            "email": $("#becomeemail").val()
        },
        type: 'GET',
        dataType: 'html', // Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
        success: function(response) {
            if (response == "true") {
                $('#emailerrorbecome').slideDown();
                $('#become-submit').prop('disabled', true);  
                $('.black-screen').hide(); /* hide it here */
            } else {
                $('#emailerrorbecome').slideUp();
                $('#become-submit').prop('disabled', false);
                this.submit(); /* 'this' refers to the FORM, and calling submit() DOM native method doesn't fire again jq handler */
            }
        },
        error: function(request, textStatus, errorThrown) {
            alert(errorThrown);

        }
    });
});

For explanation of the why , see Quentin's answer

You cannot prevent the submit long after the submit function has returned. The Ajax result occurs much later.

You can instead flag the submit (eg use a sentinel variable) and cancel it unless allowed. Then trigger a submit from code in the Ajax callback .

Example:

var allowSubmit = false;
$( "#becomesignup" ).submit(function( event ) {
    if (!allowSubmit){
        $.ajax({
            url : 'login', // Your Servlet mapping or JSP(not suggested)
            data : {"email":$("#becomeemail").val()},
            type : 'GET',
            dataType : 'html', // Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
            success : function(response) {
                if(response == "true"){
                    $('#emailerrorbecome').slideDown();
                    $('#become-submit').prop('disabled', true);
                  // Enable next submit to proceed
                  allowSubmit = true;
                  // And trigger a submit
                  $( "#becomesignup" ).submit();

                }else{
                    $('#emailerrorbecome').slideUp();
                    $('#become-submit').prop('disabled', false);
                }
                 $('.black-screen').hide();

              },
              error : function(request, textStatus, errorThrown) {
                alert(errorThrown);

            }
        });
    }
    // return false does e.preventDefault(), and true allows it to proceed
    return allowSubmit;
});

You are calling preventDefault to late.

Order of execution is this:

  1. Event handler fires
  2. HTTP request is sent
  3. Event handler finishes
  4. Prevent Default was not called so the default behaviour occurs
  5. HTTP response is recieved
  6. Success handler fires
  7. Prevent Default is called … too late to have any effect

You can't wait for the HTTP response to come back before preventing the default behaviour.

You either need to always prevent the default behaviour and then conditionally resubmit the form with JS in the submit handler, or move the logic for when you use Ajax to perform your tests so it doesn't depend on the form submission event in the first place (eg run it as soon as the data has been entered and be prepared for the possibility that the form might get submitted before your JS has finished running).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM