Friday, July 16th 2010

wmd-editor: How to retrieve both markdown and html

You are using markdown with the wmd-editor in your application, perhaps after having discovered it thanks to stackoverflow.com. What do you post to the server, the markdown "source" or the rendered html?

You could post the html which saves you the trouble of generating the html again on the server side. But if you want to allow your users to edit the text in the future now you don't have the markdown source anymore. So then maybe it is better to post the markdown, which means you have to render it to html on your server using another server-side markdown library. However it can be that the markdown implementation for your language is not bug-free enough, or maybe just not 100% consistent with the official implementation. Or maybe you just feel that this step is redundant since you already have the html sitting ready and packed on the browser side.

So it looks that the better and simpler solution would be to post both markdown and html, but it seems wmd-editor only allows us to pick one, we can set either output:"Markdown" or output:"HTML".

However if you don't mind using javascript (and since you are using wmd-editor the answer is that you don't mind), with the help of a little jquery we can easily send both, by simply using the markdown source from the editor textarea and the html from the wmd-preview area.

var source = encodeURIComponent($('#wmd-input').attr('value'));    
var html   = encodeURIComponent($('#wmd-preview').html());    
var data   = 'Source=' + source + '&Html=' + html;

$.post('/postArticle', data, function(result) {
    // Do things based on success or failure
});

For the above to work make sure the wmd-editor is set to output:"Markdown". Also don't forget to sanitize the html on the server side.