jqueryruby-on-railsrubyrjs

Running a rails RJS template from a jquery get request


I am using Rails and jquery with RJS templates to perform various AJAX requests.

For most of my Ajax stuff I attach a submit handler to the form in my application.js as follows:

$('#tagging_flickr_photos').submitWithAjax();
$('#tag_submit').click(function() {
    $('#flickr-photos-status').show();

});

This calls the form action which does some processing and then forwards to a RJS template as follows:

$("#flickr-photos-status").hide();
$("#flickr-photos").fadeIn();
$("#flickr-photos").html("<%= escape_javascript(render(:partial => 'flickr_photos_for_tagging_content')) %>");

This works a treat.

Now I am trying to do the same but just based on selecting a different value in a dropdown and not submitting a form. Here's my javascript to attach the handler to the dropdown:

$('#film_film_name_id').change(function() {
    $.get('/admin_film/make_tags?film_name_id=' + $("#film_film_name_id").val() + '&film_speed_id=' + $("#film_film_speed_id").val());
});

My controller method does some processing then forwards to the RJS template (make_tags.js.erb):

$("#film_tags").val(<%=@tags%>)

However, the template doesn't appear to execute. I can see entries in my logs that it's calling my method and rendering the template but no matter what I put in the template nothing seems to happen. I've put a Javascript alert in there and it doesn't fire.

I assume the problem is to do with attaching my Javascript handler but I can't figure out what I am missing.

Thanks in advance for any help.


Solution

  • I think you have to tell jQuery that you are expecting JavaScript and that it should be executed. Try the following and see if it works:

    $('#film_film_name_id').change(function() {
      var url = '/admin_film/make_tags?film_name_id=' + $("#film_film_name_id").val() + '&film_speed_id=' + $("#film_film_speed_id").val()
      $.ajax({
        type: 'GET',
        dataType: 'script',
        url: url
      });
    });
    

    Please check the jQuery docs on jQuery.ajax() if it doesn't work as I haven't tested the code.