javascriptphpjqueryajaxformvalidation-plugin

call ajax function in onsubmit form


I am using html form and using php to submit this, but before submit I want to use ajax method for validation and checking response, if response true then return true else return false so till checking response html form should not get submitted but without checking response also form getting submit even I used return

<form  method="POST" action="<?= base_url('save_details/')?>" onsubmit="return validate()">

<button type="submit">Add</button>
                                                
</form>

script

function validate(){
$.ajax({
                type: "POST",
                url: "<?= base_url('validate_email') ?>",
                data: {
                    email: email,
                 
                },
                dataType: 'json',
                success: function (response)
                {
                  if (response.status) {
                        return true;
                    } else {
                        return false;
                        // some message
                    }
                }
            });
}

Solution

  • The first issue you have is that you need to prevent the standard form submission, so that your logic waits for the AJAX request before allowing the request to be sent. To do that you can use an unobtrusive event handler. Ideally these should always be used over the inline on* event attributes in your HTML, as the latter are no longer good practice.

    The second issue is due to the async request, your return statement will not actually provide a response to the validate() call. You need to work with the async pattern to allow the request to complete and perform an action based on the response.

    Lastly you can make your AJAX request and re-submit the form directly if the state of the response matches your required rules. Try this:

    <form method="POST" action="<?= base_url('save_details/')?>" data-emailvalidationurl="<?= base_url('validate_email') ?>">
      <!-- form form controls ... -->
      <button type="submit">Add</button>
    </form>
    
    jQuery($ => {
      $('form').on('submit', e => {
        e.preventDefault();
        $.ajax({
          type: "POST",
          url: e.target.dataset.emailvalidationurl,
          data: { email: email },
          dataType: 'json',
          success: function(response) {
            if (response.status) {
              e.target.submit(); // rule met, allow form submission
            } else {
              console.log('Denied...');
              // show message to user here...
            }
          }
        });
      });
    });
    

    Also note that I put the email validation URL in a data attribute in the HTML. The reason for this is the same reason why on* event attributes are bad practice - separation of concerns. You should look to not have any code other than Javascript in your .js files.