views:

516

answers:

2

I have a form I am submitting via AJAX (using prototype and the built-in rails 'form_remote_tag' helper).
What I would like is to update one div (a status area) if there are form validation errors but a different div (the div where the form lives) if the submit goes through sucessfully.

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 think of doing this is to return a HTTP error status if there is a validation error but that seems like a bit of a hack. Is there a cleaner way of doing it at all?

+1  A: 

I would check out the latest Railscasts on jQuery as well as an older episode on RJS templates. Those should get you up and running nicely with AJAX and your Rails app and making everything function correctly and cleanly without any hacks.

Having looked at your code, I would suggest using jQuery (see the episode above), you'll extract all of the javascript from your form making it a lot less obtrusive (which is a very good thing).

It seems you've got down the techniques, so you will quickly pick up on writing unobtrusive Javascript with jQuery and chances are you will end up a much happier person with a much cleaner app. :)

Good luck!

mwilliams
Are you suggesting my function returns JSON instead of a template? I did consider that as a solution but it seemed fiddly to pass the error messages back.Or are you just suggesting I swap from Prototype to JQuery?
Darren Greaves
I suggest swapping out for jQuery. No need for JSON, watch the jQuery Railscasts I linked above, it essentially explains everything you need for your task.
mwilliams
Cool, will do, thanks for the help. I wanted to look at JQuery anyway so this is a good reason to do so.
Darren Greaves
+1  A: 

I would recommend, as noted in another answer, that you look into using jQuery. However, that will require some ramp-up for sure, so sticking with Rails defaults so that you can move forward more quickly...

What you want to look into is inline RJS. Rather than do everything in the form_remote_tag call, you could do your AJAX updates from within your controller. That way, you can manage the logic of whether or not there are validation errors and execute one or another AJAX update (to whichever div) depending on that.

See this post by Jamis Buck for starters.

Yardboy
Thanks for that - I don't mind the ramp-up - the site doesn't use lots of AJAX anyway.
Darren Greaves