Created
October 17, 2013 00:48
-
-
Save blairanderson/7017526 to your computer and use it in GitHub Desktop.
Rails AJAX(remote true) Form with Custom Errors I had a form that I needed to submit with ajax, use the server to validate, then handle responses on the client. I wanted a solution that was basically agnostic to the page. Would love to see other solutions...
This file contains 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
$( document ).ready(function() { | |
$("form[data-remote]").on("ajax:success", function(e, data, status, xhr) { | |
console.log('success, yall'); | |
$("form[data:remote]").append(xhr.responseText); | |
}).bind("ajax:error", function(e, xhr, status, error) { | |
$('.errors').detach(); // removes any previous errors | |
var targetClass = $(e.target).data('targetClass'); // add data:{ 'target-class' => 'class'} to your form | |
var errors = JSON.parse(xhr.responseText); // jsonifies the errors into an object | |
var keys = Object.keys(errors); // gets the keys of the error object | |
for (var i = 0; i < keys.length; i++) { | |
var key = keys[i]; | |
var $el = $(e.target).find('.'+ targetClass +'_'+key); | |
$el.append("<label class='errors'>" + errors[key] + "</label>"); | |
}; | |
}); | |
}); |
This file contains 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
<%= simple_form_for post, remote: true, data: { 'target-class'=> 'post' } do |f| %> | |
<%= f.input :title %> | |
<%= f.input :subtitle %> | |
<%= f.input :content %> | |
<%= f.submit %> | |
<% end %> |
You might also use $(document).on('ajax:success', 'form[data-remote', function(e, data, status, xhr){ /* [...] */ });
instead of your more complex construct (provided that ajax:success propagates as far as document
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You might consider using
but the change is pretty lateral.