Skip to content

Instantly share code, notes, and snippets.

@blairanderson
Created October 17, 2013 00:48
Show Gist options
  • Save blairanderson/7017526 to your computer and use it in GitHub Desktop.
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...
$( 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>");
};
});
});
<%= simple_form_for post, remote: true, data: { 'target-class'=> 'post' } do |f| %>
<%= f.input :title %>
<%= f.input :subtitle %>
<%= f.input :content %>
<%= f.submit %>
<% end %>
@mrgenixus
Copy link

You might consider using

$.each(errors, function(error,key) {
  var message = $('<label>').addClass('errors').text(error);
  $(e.target).find('.' + targetClass + '_' + key).append( message );
});

but the change is pretty lateral.

@mrgenixus
Copy link

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