Topic: Jquery event on form added via ajax

Tricky one..

I have a form that is added to a page via a ajax call. Then I want to submit this form via ajax.
I'm using the code in the last example listed here: http://mad.ly/2007/05/17/jquery-ajax-rails/

This is the code as added to the page:

<% form_for :post, Post.new, :url => posts_path, :html => { :id => "new_post" } do |f| %>
  <%= f.text_field :title %>
  <%= f.text_area :body %>
  <%= submit_tag "Create" %>
<% end %>

In external js file called on orig page load.
<script>
$(function() {
  $("#new_post").ajaxForm({
    dataType: 'script',
    beforeSend: function(xhr) {xhr.setRequestHeader("Accept", "text/javascript");}
  });
});
</script>

The problem is that the binding between #new_post and the ajaxForm function does not happen if the form is added after the original document loads.

Anyone know anyway around this while still using jquery and not remote_form_for ?

Thanks

Re: Jquery event on form added via ajax

As usually seems to happen.. I figure out the answer shortly after posting

Some searching led to this:
http://docs.jquery.com/Tutorials:AJAX_and_Events

After much fiddling with that, I realized I didn't need an event binding or anything, just loading of the "$("#ajax_form").ajaxForm({" code after the ajax call is loaded..

So in the "success:" portion of my ajax call, I just added a new function call: bind_ajax_forms();

Then in my $(document).ready portion...

var bind_ajax_forms = function() {
    $("#ajax_form").ajaxForm({
      dataType: 'script',
      beforeSend: function(xhr) {xhr.setRequestHeader("Accept", "text/javascript");}
    });
}
bind_ajax_forms()

And it works as expected and desired..

Last edited by timmaah (2007-08-31 11:59:15)