Search code examples
jqueryruby-on-railsrubyruby-on-rails-3ujs

rails - JS callback not executed with remote JSON form (jQuery UJS)


Consider the following form in .erb view:

<%= form_tag(harvester_next_url, :method => "post", :remote => true, "data-type" => :json, :id => "answerForm") do %>
<div id="dynamicFormContent"></div>
<% end %>

In certain circumstances, I want to issue a JS callback in the next method with render :js => "window.location = '#{definitions_path}'"

However, this does not execute in browser. The response has "window.location..." in body and the content-type is set to text/javascript, the request's accept has text/javascript, too.

The Rails version is 3.2.8.

Some additional information: I don't want to switch form action to use JS format as JS callback code is only one of the possible responses from the controller. The other time, I need some JSON from it to deal with.

The question: is there a possibility to make it work without using client-side redirection (i.e. getting window.location from JSON response), etc.? AFAIK, this works OK for non-remote forms.

ADD It ends up with status = "parsererror" when XHR completes. Clearly, this is because jQuery attempts to parse response as JSON, even though it's text/javascript. The question is still open.


Solution

  • Finally I've got it working. However, I've realized that it is generally a dirty approach (you all told me so) to execute incoming JS as-is. But, as long as my question was about that dirty approach, I'll post an idea of how to make it work if you really need it.

    Given that we have parsererror status in case we supply plain JS, we can:

    $('#answerForm').on('ajax:error',
      function(e, data, status, xhr)
      {
        $.globalEval(data.responseText);
      }
    );
    

    Thanks everyone!