Abdullah Diab’s Blog

Simple AJAX Comment Preview in Drupal 6

As I said in my previous post, I’m working on upgrading Computer Science in Syria website to Drupal 6.

I wanted also to have AJAX comment preview in nodes, but I wanted it to be simple without lots of JavaScript loaded. So as usual I got pissed off and decided to create my own code to do it. 8)

I used Simple Modal by Eric Martin to display the preview in a model instead of a new page.

The code is easy too like the previous post’s code, I edited also the drupal.js file and added the following code:

if (location.pathname.match('^' + Drupal.settings.basePath + 'node/\\d')) {
		$('#edit-preview').click(function () {
			$.modal('<div><h1>Preview</h1><div id="previewContent"><img style="width: 126px; height: 22px;" class="previewing" src="' + Drupal.settings.basePath + 'misc/previewing.gif" alt="Loading ..." /></div></div>');
			var comment = $('#edit-comment').val();
			if ($('#wysiwyg-toggle-edit-comment').text() == Drupal.settings.wysiwyg.disable) {
				$('#wysiwyg-toggle-edit-comment').click();
				comment = $('#edit-comment').val();
				$('#wysiwyg-toggle-edit-comment').click();
			}
			$.post(
				$('form#comment-form').attr('action'),
				{
					'comment' : comment,
					'form_build_id' : $('form#comment-form input[name="form_build_id"]').val(),
					'form_id' : 'comment_form',
					'form_token' : $('form#comment-form input[name="form_token"]').val(),
					'op' : $('form#comment-form input#edit-preview').val(),
				},
				function (html) {
					$('div#previewContent img').remove();
					$('div#previewContent').append($(html).children().find('div.preview div.content').html());
					$('form#comment-form input[name="form_token"]').val($(html).children().find('form#comment-form input[name="form_token"]').val());
					$('form#comment-form input[name="form_build_id"]').val($(html).children().find('form#comment-form input[name="form_build_id"]').val());
				}
			);
			return false;
		});
	}

The process is too simple:

  1. @line 01: I check to see if the current page is a node page, I just want to make the preview code working on node page.
  2. @line 03: I show the user a modal with a loading image Loading …
  3. @lines 04~09: I check the editor, if it is enabled I disable it to get the HTML from the comment. If it is not enabled I get the HTML directly without disabling it.
  4. @lines 10~18: I gather the data of the form and post them.
  5. @line 20: I remove the loading image.
  6. @line 21: I append the HTML data from the response to the modal content.
  7. @lines 22~23: I set the form hidden values (form_build_id and form_token) to the values from the response so I don’t get a Validation Error.
  8. @line 26: I return false so the browser doesn’t post the data again to the new page.

Here is an example:

Simple 😉