form validaiton on form submit without page reload

Solution:1

What you need to do is in your jQuery code, pass the data retrieved from the call to the success function like so:

success: function(data){
    //Do something
}

That data variable will then contain whatever PHP has echo’d. If you want to access that data in some meaningful way, it will be easiest if you prepare it as an array in PHP i.e. like so:

$dataForjQuery = array('status' => 'OK', 'message' => 'validation passed');
echo(json_encode($dataForjQuery));

this way in jQuery you would do:

success: function(data){
    console.log('the status is: ' + data.status); //Will log 'the status is: OK'
    console.log('message from server: ' + data.message); //Will log 'message from server: validation passed'
}

Solution:2

Sometimes, when a form is submitted, you don’t want to reload the page, instead you want to execute a javascript function only. Here are ways of executing a javascript function on form submit without reload the html pagereturn false; is the key to prevent the from to reolad the html page.

1. When this html form is submitted, it will call the javascript function yourJsFunction(), but it won’t reload the page.

1
2
3
4
<form action="#" onsubmit="yourJsFunction();return false">
    <input type="text"/>
    <input type="submit"/>
</form>

 

2. Use jQuery’s submit event to handle the form submit, add return false; at the end of the submit handle function to prevent the page to reload.

1
2
3
4
5
<form action="" id="my-form">
    <input type="text"/>
    <input type="submit"/>
</form>
1
2
3
4
5
6
$(document).ready(function() {
    $(document).on('submit', '#my-form', function() {
      // do your things
      return false;
     });
});

 

3. This form has no submit input, thus it won’t reload the page because the form will never get submitted, but the javascript function will be executed the button input is clicked.

1
2
3
4
<form action="#">
    <input type="text"/>
    <input type="button" onclick="yourJsFunction();"/>
</form>