Updating different divs from AJAX depending on validation errors

I have a form that I am submitting via AJAX (using the prototype and the inline "form_remote_tag" helper).
I would like to update one div (the status area) if there are form validation errors, but another div (the div where the form is located) if the submission is successful.

My code looks something like this:

<div id="recipe-status"><!-- I want form validation errors to go here --></div>
<div id="recipe">
    <%= form_remote_tag(:update => "recipe-status",
       :before => "Element.show('wait-indicator')",
       :success => "Element.hide('wait-indicator')",
       :complete => visual_effect(:appear, "recipe-status"),
       :url => { :action => 'import', :id => @recipe.id },
        :failure => "alert('Unable to import recipes at present')") %>
    <-- Form goes here, I want this to be replaced if the submit succeeds -->
</div>

      

The only way I can do this is to return the HTTP error status if there is a validation error, but that looks like a hack. Is there a cleaner way to do this at all?

+1


source to share


2 answers


I would look at the latest Railscasts on jQuery as well as an older episode on RJS templates . They should fit you well and work with AJAX and your Rails application and do it right and cleanly, no hacks.

After looking at your code, I would suggest using jQuery (see episode above), you will be extracting all the javascript from your form to make it much less intrusive (which is pretty good).



You seem to have methods, so you'll quickly pick up some unobtrusive Javascript with jQuery, and chances are you'll be a much happier person with a much cleaner application. :)

Good luck!

+1


source


I would recommend, as noted in another answer, that you are looking at using jQuery. It will take some uplift though, so stick with Rails by default so you can move forward faster ...

What you want to learn is the built-in RJS. Instead of doing everything in the form_remote_tag call, you can do your AJAX updates from your controller. This way you can control the logic of the presence or absence of validation errors and perform one or the other AJAX update (depending on which div) depending on that.



See this post by Jamis Buck for a start.

+1


source







All Articles