Drupal 6: Embedding a Drupal search form on another site using jQuery

In this tutorial I'll show you how you can expose your search form on another site using jQuery. At first, I thought about scraping the form's html using AJAX.. and quickly remembered you cannot easily do that. Which lead me to review the AJAX functionality included in jQuery. Bingo, one of my favorites: jQuery.getJSON. To summarize this code, I create a callback function to display the form's json-ified html which can then be easily embedded on another site.

First I defined the menu hook:

<?php
function MYMODULE_menu() {

  $items = array();

  // add a page callback for the url: "external-search.js"
  $items['external-search.js'] = array(
    'page callback' => '_MYMODULE_external_search',
    'type' => MENU_CALLBACK,
    'access arguments' => array('search content'),
  );

  return $items;

}
?>

Then I created the callback function for the menu callback:

<?php
function _MYMODULE_external_search() {

  // create a json string of the search form html
  $json = drupal_to_js(drupal_get_form('search_form'));

  // format the json as a callback function
  // see: http://docs.jquery.com/Ajax/jQuery.getJSON for more information
  if ($_GET['jsoncallback']) {
    $json = $_GET['jsoncallback'] . "(" . $json . ");";
  }

  // output the json
  print $json;

  // stop the script, so the theme layer is not applied
  die;
}
?>

One problem though, the form submits locally. That can be fixed using a form_alter function:

<?php
function MYMODULE_form_alter(&$form, $form_state, $form_id) {

  // check for external search form and set form action to be full path
  if ($form_id == 'search_form' && arg(0)=='external-search.js') {
    // change the form action to be the full path
    $form['#action'] = 'http://' . $_SERVER['HTTP_HOST'] . $form['#action'];
  }
}
?>

Now if you clear your cache and go to http://YOURSITE/external-search.js, you should see the JSON (and nothing else).

Last you can embed the code on another site using a few lines of jQuery. You can even pull the jQuery from your site if the external site does not have jQuery included.

<!-- Include jQuery (as necessary) -->
<script type='text/javascript' src='http://YOURSITE/misc/jquery.js' ></script>

<!-- create a div container to contain the search form -->
<div id='embedded_search'></div>

<!-- add the jQuery to embed the form -->
<script type='text/javascript'>
$(document).ready(function(){
  // make the ajax request
  $.getJSON("http://YOURSITE/external-search.js?jsoncallback=?",
    function(data){
      // append the form to the container
      $('#embedded_search').append(data);
    }
  );
});
</script>

Now people should be able to access your site's search form from another site.