Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
PHP: _POST + Valitron + Bootstrap (or any other front-end framework)
<?php
// Please use better solutions (see Slim3 Framework), check CSRF/Xhr, use Except, etc.
// This is only an example!
if ($_POST)
$v = new Valitron\Validator($_POST);
$v->rule('required', title');
//$v->rule..
if (!$v->validate())
exit(json_encode(array('error' => $v->errors())));
// Check double Title
if (chkExists($_POST['title']))
$e['title'] = array('Title already exists'); // result: ['title'][0] => 'Title already exists';
// extra checks
// On errors ..
if (!empty($e))
exit(json_encode(array('error' => $e)));
// do something
// Alert
//exit(json_encode(array('status' => 'warning', 'out' => '<strong>This is a warning!</strong>')));
// Success => replace form
exit(json_encode(array('status' => 'replace', 'out' => '<h1>Success!</h1>')));
}
// Twig
$twig = new Twig();
$twig->render('example.twig');
<form method="post" action="my/process/url" id="ajaxForm">
<!-- show alert here -->
<div class="form-group">
<label for="title">Title</label>
<input type="text" name="title" class="form-control" id="title" placeholder="Movie Title" value="{{ title }}">
<!-- show field message (help-block) here -->
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<script src="js/jquery.form.js"></script>
jQuery.fn.writeMessages = function(type,list) {
$.each(list, function(key, value) {
$("label[for='"+ key +"']").parent().addClass('has-' + type);
$.each(value, function(subKey, subValue) {
$("label[for='"+ key +"']").parent().append('<span class="help-block">' + subValue + '</span>');
});
});
};
$('#ajaxForm').submit(function(event) {
event.preventDefault();
$.ajax({
type: "post",
cache: false,
url: $(this).attr('action'),
dataType: "json",
data: $(this).serialize(),
success: function (response) {
$(".alert").remove();
$(".help-block").remove();
$(".form-group").removeClass('has-error has-warning has-success');
if (response.status === "replace") {
$('#ajaxForm').html(response.out);
} else if (response.status === "danger" || response.status === "warning" || response.status === "success" || response.status === "info") {
$('#ajaxForm').prepend('<div class="alert alert-' + response.status + '">' + response.out + '</div>');
} else {
$.each(response, function(key, value) {
$('#ajaxForm').writeMessages(key, value);
});
}
}
})
return false;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment