php jquery ajax for form validation but not for submit

Viewed 328

Considering the following very basic form:

 <form action="action_page.php" method="post">
   <input type="text" id="fname" name="fname"><br><br>
   <input type="text" id="lname" name="lname"><br><br>
   <input type="submit" value="Submit">
</form> 

I know how to validate and submit this form using jquery ajax. My question: is there anyway I could first validate the form using ajax before submitting it the regular way to the action php file?

I mean the two processes should be the result of the submit action.. ie the script called should first validate and when all ok then submits the page to the file in the form action attribute or to any url I specify. Otherwise it halts form submit returning the error messages.

Thanks

2 Answers

This litle code works fine. If your ajax call is ok, then submit form. Is that the question?

Update your form (note type button in place of type submit)

<form name="action" id="action" action="action_page.php" method="post">
   <input type="text" id="fname" name="fname"><br><br>
   <input type="text" id="lname" name="lname"><br><br>
   <input type="button" id="submit_button" value="Submit">
</form>

And your js

$('#submit_button').on('click', function(e) {

  // Do your ajax call
  $.ajax({
    url:'myurl.php',
    type:'GET',
    success: function(data) {
      $('form').submit();// Finally submit
    },
    error: function(xhr, status, error) {
      alert('Ajax error');
    }
  });
  
});

https://jsfiddle.net/p6xrm1d0/14/

You can use javascript's onsubmit event.

<form action="action_page.php" method="post" onsubmit="return validateForm()">

and your js function will look something like this

function validateForm(){

 //perform all the validations and based on the validation return true or false.
 
 // you can use JQUERY within this to set the error divs or alerts etc
}
Related