Question

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.

Was it helpful?

Solution 2

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!

OTHER TIPS

Listen for the callback and do the redirect on the client side:

$('#answerForm').on('ajax:success', function(data) {
  if (data.url) {
    window.location = data.url;
  } else {
    // do something else...
  }
})

# -- controller code
render json: {url: definitions_path}

If you ask for json, it won't be rendered as javascript immediately, which means you'd need to grab the url from the json response, for instance a 'next-url' key. You can do that in the ajax callbacks.

Here's some reading that should make what you're trying to do easy:

Rails ujs tutorial (with the callbacks): http://www.alfajango.com/blog/rails-3-remote-links-and-forms/

How to respond to json RESTfully: Rails 3: What is the proper way to respond to REST-ful actions with JSON in rails?

Also to detect xhr: Rails detect if request was AJAX

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