jqueryajaxformspreventdefaultsubmission

preventDefault() not working for preventing submission of form


Using JavaScript to check for the submission of a form, perform an ajax call to check for a project name. If the response is true ("the project name exists") then I want to cancel the submission of the form and show an error.

For some reason prevent Default is not doing anything to prevent the refresh of the page, or the submission of the form. I successfully enter the if statement every time I test it, however the page is refreshed and form is submitted.

JS

$( document ).ready(function() {
    // If the project entered already exists in our database, Cancel submission.
    $('#add-project-form').on("submit", function(event){
        console.log("SUBMITTING...");
        let project_name = $('#project_ea').val();
        $.ajax({
            url: "api/Projects/ProjectExists/" + project_name,
            type: "POST",
            dataType: "json",
            success: function(data){
                console.log(data);
                console.log(event);
                if (data == true){
                   //Prevent Submission of form
                   event.preventDefault();
                   console.log("Submission Halted.");
                   $('#project-name-error').show();
               }  

            }
        }); 
    });
});

Button being pressed

<button type="submit" form="add-project-form" name="add-project-form-button" id="add-project-form-button" class="btn btn-primary">Save changes</button>

Solution

  • You have to use event.preventDefault() before you send a request to the API. Since, API call is asynchronous, before event.preventDefault() in the success method executes, the page gets reloaded already

    Edit: you can prevent default at the start of the event handler and submit the form when data is true

    $( document ).ready(function() {
    // If the project entered already exists in our database, Cancel submission.
    $('#add-project-form').on("submit", function(event){
        event.preventDefault(); //prevents
        console.log("SUBMITTING...");
        let project_name = $('#project_ea').val();
        $.ajax({
            url: "api/Projects/ProjectExists/" + project_name,
            type: "POST",
            dataType: "json",
            success: function(data){
                console.log(data);
                console.log(event);
                if (data == true){
                   //Prevent Submission of form
                   //event.preventDefault();
                   document.querySelector('#add-project-form').submit(); //you can submit the form using this function
                   console.log("Submission Halted.");
                   $('#project-name-error').show();
               }  
    
            }
        }); 
    });
    

    });