Skip to content

Instantly share code, notes, and snippets.

@kamaroly
Created December 14, 2016 09:06
Show Gist options
  • Save kamaroly/627d3f5b130e435c9909212051ebeb60 to your computer and use it in GitHub Desktop.
Save kamaroly/627d3f5b130e435c9909212051ebeb60 to your computer and use it in GitHub Desktop.
When you have a laravel project with a form and you would like to make jquery ajax form submit and validation, you can use below codes,
$(function(){
$('.form-horizontal').on('click', function(e){
e.preventDefault();
var $form = $('.form-horizontal');
var url = $form.attr('action');
var method = $form.attr('method');
$.ajax({
url: url,
type: method,
data: $form.serialize(),
success: function(data){
alert("Successfully submitted.")
},
error: function (response) {
var errors = JSON.parse(response.responseText);
//handle failed validation
associate_errors(errors, $form);
}
});
});
function associate_errors(errors, $form)
{
//remove existing error classes and error messages from form groups
$form.find('.form-group').removeClass('has-errors').find('.help-text').text('');
$.each( errors, function( key, value) {
console.log(value);
// errorString += '<li>' + value + '</li>';
// find each form group, which is given a unique id based on the form field's name
var $group = $form.find('#' + key);
//add the error class and set the error text
$group.addClass('has-errors').text(value);
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment