[support] How would I do an ajax call within my own custom module?

Seth Freach sfreach at gmail.com
Wed Apr 14 22:25:30 UTC 2010


John Mitchell wrote:
> How would I do an ajax call within my own custom module?
>
> Thanks,
>
> John
>
>   
You will probably need 2 menu items:
 - The first to define the page that will be the ajax client.  Ie, the 
url of the page that this all happens on, a regular drupal page that has 
called drupal_add_js() to add some JS code that will do a $.ajax({...}); 
call (or other jquery asynchronous call).  This menu item might not be 
needed though if the JS is added in a block, or inserted via 
hook_form_alter or hook_nodeapi, etc.
 - The second menu item will define the ajax server.  It should be 
'type'=>MENU_CALLBACK and have the appropriate access checks defined as 
well.  The callback function associated with this path should, instead 
of returning themed output, end with: drupal_json(array(...)); exit();  
where the array(...) is an associative array that you want to hand back 
to the calling page in JSON format.

If you're doing this for D7, look at: 
http://api.drupal.org/api/drupal/developer--examples--ajax_example--ajax_example.module/7

Seth


More information about the support mailing list