views:

44

answers:

1

I'm sure this is a really simply question, and I apologize if it is...

I'm using Rails 3 and jQuery, and am trying to bind an ajax:success to a remote form submission. The data that is being returned by the function will be in JSON format - and for some reason, I CAN NOT ACCESS the data. I don't understand how to fix it. Here's where I create the form:

Search: <%= form_tag(configurations_url(:format => :json), :remote => true, :method => :get) do %>
    <%= text_field_tag :query %><br />
    <%= submit_tag "Search"%>
<% end %>

And then, on the bottom, I have this jQuery written to attach a function to the tail:

jQuery("document").ready(function() {   
    jQuery("div#configuration_search_form form").bind('ajax:success', function(json) {
        select_tag = jQuery("div#configuration_select_form form select")
        select_tag.empty()
        none_found_div = jQuery("div#no_configurations_found")
        select_form_div = jQuery("div#configuration_select_form")
        none_found_div.slideUp();
        select_form_div.slideUp();

        if(json.length > 0) {
            jQuery.each(json, function(index, config) {
                option_tag = "<option value='" + config.configuration.id + "'>" + config.configuration.name + "</option>"
                jQuery(option_tag).appendTo(select_tag)
            })
            select_form_div.slideDown();
        } else {
            none_found_div.slideDown();
        }
    })
}

So, the data that is being returned is json data, and it's perfectly valid. In fact, if I just write an ajax function by hand on the bottom, it works fine (that is, instead of using ajax:success, I just wrote an jQuery.ajax to react to a submit), but I'd rather not have all the extra code, since the form with the remote tag is so tidy. Is tehre a way I can fix this?

EDIT:

To clarify - what happens is, there is no error, but even if results are returned, it takes the trunk to unhide the 'no results found' div.

A: 

Not sure, but maybe the problem is that you're expecting the wrong number of arguments for your ajax:success callback. Try:

jQuery("div#configuration_search_form form")..bind("ajax:success", function(json, status, xhr) {
      // Your code here...
    });

Probably first put an alert on json.toSource() and status and see what you get.

Redbeard
Good suggestion - I had the three vars in before, and in my experimenting, forgot to put them back. Sadly, same results when I put them in. Thanks though! Any other ideas?
jasonpgignac
What's the status var contains on the response?
Redbeard
OK, after looking at my objects more closely, using the jQuery.dump plugin, it turns out I had the argument order mixed up: should be xhr, json, status. So, I was looking at the request object, not the return data. The original example I had learned from had things in the wrong order. Thanks so much for your help!
jasonpgignac