Thursday, March 3, 2011

How to submit an ajax form in javascript with Rails3 and Prototype

So there is a Rails 3 problem, when you want to submit a form in javascript (without a submit button), it is working on normal way, not ajax. But we can do creating a hidden submit button and then initializing a click event on it what is exactly doing ajax submission. The submit(); is not working anymore because it doesn't call the rails.js functions. It just works when you simple want to create a not ajax post without any confirmation. Let's see an ajax example in view's index.html.erb file:

<%= form_tag "some_url",
 :remote  => true,
 :method  => :post,
 :name  => "some_procedure",
 :id   => "some_procedure" %>
<%= submit_tag 'procedure_submit_button', :id =>"procedure_submit_button" , :style => "display: none" %>

You can add here your html code for form and create some element what is doing the submission inside a table, for a td:

<td onclick="javascript: procedure_init();" style="cursor: pointer;">

put here an image for example

</td>

</form>

<%= javascript_tag <<-RUBY
function procedure_init()
{
 var submit_button="procedure_submit_button";
 var form_name="some_procedure";
 // here you can build the form, or modify form parameters
 $(submit_button).click();
}
RUBY
%>

If you have problems with sessions or current_user quits within ajax rendering, put this code to public/javascripts/application.js. /thanks to this answer/

document.observe("dom:loaded", function() {
 Ajax.Responders.register({
  onCreate: function(request) {
   var csrf_meta_tag = $$('meta[name=csrf-token]')[0];
   if (csrf_meta_tag) {
    var header = 'X-CSRF-Token',
      token = csrf_meta_tag.readAttribute('content');

    if (!request.options.requestHeaders) {
     request.options.requestHeaders = {};
    }
    request.options.requestHeaders[header] = token;
   }
  }
 });
});

That's all. Questions?

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.