-
-
Save raank/1843f0ae1ad6b68b697e87d9464ee7aa to your computer and use it in GitHub Desktop.
Código de form via ajax
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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