A form can be submit and validate without refreshing with the help of ajax and jquery. You just need to include one ajax file and there is no need of any js validation file to check the validations.Validation can be done on the basis of ajax response and will be display under particular field for which that error occurs.
Here are the sample html form code and jquery code to initiate and handle the ajax programming to handle form processing.
<div class="abc">
<h1>Processing an AJAX Form</h1>
<form action=" " id="customForm" method="POST">
<div id="name-group">
<label for="name">Name</label>
<input type="text" name="name" placeholder="Enter Name">
</div>
<div id="address-group">
<label for="address">Address</label>
<input type="text" name="address" placeholder="Enter address">
</div>
<button type="submit" >Submit </button>
</form>
</div>
/*** jquery code ***/
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> <!-- load jquery via CDN -->
<script type="text/javascript">
$(document).ready(function() {
$('#customForm').submit(function(event) {
var formData = $( "form" ).serialize();
$.ajax({
type : 'POST',
url : 'form_process.php', // the POST url on which data will be processed
data : formData, // all the form values to be send for processing
dataType : 'json',
encode : true
})
.done(function(data) {
$('#name-group').removeClass('has-error');
$('#address-group').removeClass('has-error');
console.log(data);
if ( ! data.success) {
if (data.error.name) {
$('#name-group').addClass('has-error'); // add the error class to show red input
$('#name-group').append('<div class="help-block">' + data.error.name + '</div>');
// The above error message wiill be shown under name div
}
//validation errors for name address
if (data.error.address) {
$('#address-group').addClass('has-error'); // add the error class to show red input
$('#address-group').append('<div class="help-block">' + data.error.address + '</div>');
// The above error message wiill be shown under address div
}
} else {
$('form').append('<div class="alert alert-success">' + data.message + '</div>');
}
});
// avoid form submitting in default way and page refresh.
event.preventDefault();
});
});
</script>
/* the form will be processed in a php file where you can insert , update or process the data internally which are sent from ajax request. */
<?php
$error = array(); // hold validation errors
$data = array(); // send back data
if (empty($_POST['name']))
$error['name'] = 'Name is required.';
if (empty($_POST['address']))
$error['address'] = 'address is required.';
// return a response
if ( ! empty($error)) {
$data['success'] = false;
$data['error'] = $error;
} else {
$data['success'] = true;
$data['message'] = 'Success!';
}
// You can do the db insertion or updation here and return all our data to an AJAX call
echo json_encode($data);
?>
0 Comment(s)