Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Bootstrap + jQuery (Ajax Submit) + PHP
<form id="myForm">
<div class="form-group">
<label for="title">Title</label>
<input type="text" name="title" class="form-control" id="title" placeholder="Title">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea id="description" name="description" class="form-control" rows="3"></textarea>
</div>
</form>
<script>
// Result: http://getbootstrap.com/css/#forms-control-validation
$("#myForm").submit(function(e) {
$.ajax({
cache: false,
url: 'process.php',
type: 'POST', // PUT, PATCH, ..
dataType: "json",
data : $("#myForm").serialize(),
success: function(response) {
if (response.type == 'success') {
// alert, redirect, ..
}
else {
$(".validate-block").remove();
$(".form-group").removeClass("has-warning has-error has-success");
$.each(response, function() {
$.each(this.valid, function(k, v) {
$("label[for='"+ k +"']").parent().addClass("has-" + v.type).append('<p class="help-block validate-block">' + v.msg + '</p>');
});
});
}
}
});
e.preventDefault();
});
</script>
<?php
$body['response'] = [
'valid' => [
'title' => [
'msg' => 'This is an warning',
'type' => 'warning'
],
'description' => [
'msg' => 'This is an error',
'type' => 'error'
]
]
];
header('Content-Type: application/json');
echo json_encode($body);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment