Question

I have a form on my index page that I'm using to sort records, I wanted to add some Ajax functionality to it but for some reason it's not sending my form parameters as soon as I added Ajax to the mix.

Here's my form:

<div id="sort-options">
    <%= form_tag uploads_path, :method => "get", :remote => true do %>          
            <%= select_tag "sort", options_for_select([["Creation Date", "created_at"], ["File Name", "name"], ["Rating", "rating_average"], ["Downloads", "downloads"]]) %>
            <%= select_tag "direction", options_for_select([["Descending", "desc"], ["Ascending", "asc"]]) %>                   
            <%= submit_tag "Sort" %>
    <% end %>   
</div>

And my Ajax javascript:

jQuery(document).ready(function($) 
{ 
    $(function () {  
        $('#sort-options input, .pagination a').live("click", function () {  
            $.get(this.href, null, null, 'script');  
            return false;  
        });  
    });

});

When I click the submit button and look at my Firebug console to see what's happening it's clear that it's succesfully calling the Ajax and it serves the page no problem. However it completely ignored my params that are sent and it doesn't take that into account when it re-queries the database. If I take out the ':remote => true' and remove the link to the Ajax file the params succesfully get sent back to the index action - just no Ajax :(

I should add that the Ajax currently works for pagination that I have on the very same page.

Was it helpful?

Solution

The problem is that you bind another click handler to your submit button which overrides Rails's built-in AJAX functionality (:remote => true). Your selector #sort-options input, .pagination a matches not only pagination links, but also the submit button of the form. Buttons do not have href attributes, which is what you pass to $.get() as a URL. So $.get(this.href, ...) tries to make an AJAX GET request to a null URL (which acts as if it was an empty string, thus the current URL, without any GET params).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top