0

I have a scenario where I need to show the preview of form in a new window.

I am stuck on how to invoke the rails action preview from javascript function and how to launch a new window for that action.

Here's the code:

click preview link code:

<%= link_to_function "#{image_tag('preview.png', :alt=>'Preview', :title=>'See a preview')}
<span class='text'>Preview</span>",
 "javascript:show_form()" %>

javascript function:

function show_form() {
    //grab the dom
      var html = $('#newform').clone();
    //whats next here?????
}

 rails action:

 def preview
    @html = params[:html]
 end

My question is:

  • How do I call the rails action preview?
  • how do I launch a new window with the preview for that action?

thanks for your help

Edit:

I am able to post data using $.post('/url') from jquery. However, the view is not being rendered. I can see that the view is being called(debug hits the breakpoint) but the browser does not render it. Is there anything I need to do in the .post() method to route to the new url?

2
  • You have to setup a route in Rails that corresponds to the preview action and make an AJAX call to it in show_form(). Commented Aug 26, 2011 at 19:51
  • I am able to post data using $.post('/url') from jquery. Commented Aug 27, 2011 at 0:49

1 Answer 1

3

Since you're using jQuery, you might as well use its AJAX libraries: http://api.jquery.com/category/ajax/

In most cases, using $.get() or $.post() is sufficient. You can use $.ajax() for more flexibility, at the cost of having to type out more options.

Basically your goal is to call the URL that maps to the appropriate controller action. That action should return a view with the appropriate HTML, XML, or JSON. If it just returns the HTML for the form, you can use jQuery on the result to get the appropriate values and do what you need to do with them.

EDIT:

The AJAX calls take a success callback function that you can provide to actually render the form.

Example:

$.post('/url', function (data) {
    $('#myForm').html(data); // this would simply inject the returned HTML into the form
});

EDIT (again):

Just reread your question. Seems you're trying to render everything in a new window? Assuming your view renders an entire block of HTML (with DOCTYPE and <html>), you can use window.open and just specify the URL. You don't need AJAX at all in that case.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Post seem to work in posting successfully but the view is not rendered. I will update my question with details. thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.