Question

I would like to have a live preview similar to the one here on stackoverflow. Using Rails 3.1 and RedCloth, I can not seem to understand how to make it work.

I tried making my own Ajax call such as this (inside my posts.js.coffee)

$ ->
 $('#post_content').keyup ->
  $.post('posts/preview', $('#post_content').val(), null, "script")

and having a function inside the controller

def preview
 @content = params[:post_content]

 respond_to do |f|
  f.js
 end
end

in preview.js.erb I put

$("#preview").html("<% raw RedCloth.new(@content).to_html %>");

I added the resource

resources :post do
 post 'preview', :on => :collection
end

but it doesn't work. Any suggestions?

Was it helpful?

Solution

Thanks everyone for your words of wisdom, eventually I did what you guys said, as it was far wiser to parse the preview on the client-side. I switched to Markdown parser (server-side) bluecloth 2.1.0 and

gem "bluecloth", "~> 2.1.0"

and as for the client-side parser I used PageDown

then I only needed to add a little snippet to make it work.

converter = new Markdown.Converter()
$ ->
  if $('#post_content').val() isnt ''
   $('.preview').empty().append(converter.makeHtml($('#post_content').val()))
$ ->
  $('#post_content').keyup ->
    $('.preview').empty().append(converter.makeHtml($('#post_content').val()))

notice it is not sanitized!

OTHER TIPS

You've specified "script" as the data type, which should make the response run as JavaScript. Check whether the response is correct by writing:

$.post('posts/preview', $('#post_content').val(), ((js) -> console.log js), "script")

There are some important caveats with the "script" data type approach. As the jQuery.ajax docs say, "This will turn POSTs into GETs for remote-domain requests." I'm assuming this is a same-domain request, but that's worth keeping in mind.

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