Skip to content

Instantly share code, notes, and snippets.

@raank
Created October 17, 2016 02:57
Show Gist options
  • Save raank/1843f0ae1ad6b68b697e87d9464ee7aa to your computer and use it in GitHub Desktop.
Save raank/1843f0ae1ad6b68b697e87d9464ee7aa to your computer and use it in GitHub Desktop.
Código de form via ajax
// controller
if( $validator->fails() ) {
return response()->json( $validator->errors()->fails(), 200 );
} else {
return response()->json( [
'success' => 'true',
'message' => 'Contato enviado com sucesso!'
], 200);
}
// javascript
$('#idDoMeuForm').on('submit', function() {
$.ajax({
url: 'http://localhost:8000/url/para/a/rota',
method: 'POST',
success: function( response, textStatus, jqXHR ) {
// message vem da key 'message' no response de sucesso do controller.
$('.alerta').text(response.message);
},
error: function( response, textStatus, jqXHR ) {
// response.responseText = array de erros
var error = $.parseJSON(response.responseText);
var msg = '';
var i = 0;
while (i < error.message.length) {
msg += '- ' + error.message[i] + '<br>';
i++;
}
$('.alerta').text(msg);
}
});
// para não recarregar a página.
return false;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment