How can I use jQuery UJS to submit a form via AJAX after the change event of a select box fires in Rails?

How can I use jQuery UJS to submit a form after the change event of a select box fires in Rails?

My view looks like this:

<% for perm in @permissions %>
  <%= form_for [@brand,perm], { :remote => true } do |f| %>
    <tr id="permission_<%= perm.id %>">
      <td><%= perm.configurable.name %></td>
      <td><%= f.select :action, ['none', 'read', 'update', 'manage'] %></td>
    </tr>
  <% end %>
<% end %>

Pretty straightforward. My controller is like so:

class PermissionsController < ApplicationController

    before_filter :authenticate_user!

    respond_to :html, :js

    load_and_authorize_resource :brand
    load_and_authorize_resource :permission, :through => :brand

    def index
    end

    def update
      @permission = Permission.find(params[:id])
      @permission.update_attributes(params[:permission])
    end

end

And in my application.js:

// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
$(function() {
  $("#permission_action").change(function() {
    this.form.submit(); // This needs to be an AJAX call, but how?
  });
})

Please note that the form submission fires just fine. But it is doing a regular post rather than an AJAX submission. When I place a submit button on the form and use that, the AJAX submission works fine. I need to change:

this.form.submit();

to an AJAX call, but I don't know how. Can anyone help?

Answers


I see you are already using jQuery that's good. Following code was taken from here: http://railscasts.com/episodes/136-jquery

I strongly advise you get familiar with these screen casts they help a ton (understatement).

// public/javascripts/application.js
jQuery.ajaxSetup({ 
  'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
})

jQuery.fn.submitWithAjax = function() {
  this.submit(function() {
    $.post(this.action, $(this).serialize(), null, "script");
    return false;
  })
  return this;
};

$(document).ready(function() {
  $("#new_review").submitWithAjax();
})

Looking through the jquery-ujs sources, i figured that this might be the safest way:

// in application.js
jQuery.fn.ajaxSubmit = function() {
    this.trigger('submit.rails');
};

it just fires the event as would .submit() but in a ujs flavour, so you would call

$('.my_form').ajaxSubmit();

Need Your Help

LoaderLock was detected, and turning off the warning does not help

c# directx mda loaderlock

I am trying to write an application that takes in sound from the default audio recording device on a computer. When running any code that accesses DirectX from my managed code i get this error:

Share a scope between Jersey Servlet and JSF Backing Bean

jsf jersey java-ee-6 cdi

I just want to ask if anybody has done something like this. Basically, it's like paypal express checkout functionality: