2

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?

gmaliar
  • 5,294
  • 1
  • 28
  • 36
  • 2
    Ajax is going to have too much latency for a live preview like Stack Overflow's. What you want is a JavaScript markdown library. See http://stackoverflow.com/questions/134235/is-there-any-good-markdown-javascript-library-or-control (Note that you can also run that same markdown library on the server using ExecJS, which of course comes bundled with Rails 3.1.) – Trevor Burnham Sep 18 '11 at 17:06
  • 1
    I believe this question is related: http://stackoverflow.com/questions/5311247/rails-ajax-js-erb-rendered-as-text-not-js – Trevor Burnham Sep 18 '11 at 17:15
  • In the future, Guy, it would be wise to include some debugging information. *Why* doesn't it work or what *does* it do that is unexpected? – coreyward Sep 18 '11 at 18:25

2 Answers2

3

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!

gmaliar
  • 5,294
  • 1
  • 28
  • 36
  • hey Guy.. I am trying to do the same as you. I found that using this parser is great! EXCEPT, when I write converter.makeHtml(string) into a file eg main_file.js it causes other scripts that are run later to not work. Did you find this ever? – jay Dec 10 '11 at 19:37
0

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.

Trevor Burnham
  • 76,828
  • 33
  • 160
  • 196