2

With every drupal site I make, I usually create a custom module that I use to hold different php functions and other things custom to the site I am working on. It usually only consists of a module_name.module and module_name.info. Additionally, I always have .js file in the theme to do any javascripts I might need. Pretty standard right? But I have now run into a situation where I need the two to talk to one another.

I know you can call a .php file and pass it data using .ajax in jquery. How would I envoke a function written in my custom module from the js file in my theme?

1

Hopefully this will help -- got this code from a Lullabot module development training.

It all revolves around a hook_menu callback. The value in 'page callback' is the function that will be called, in this case it is: "menu_magic_page"

So Drupal looks for the menu_magic_page() function.

Your jQuery / AJAX call would then reference the value what's in $items['X'] where X is "magic" here. So hitting http://example.com/magic would run the module function "menu_magic_page"

FWIW: the type/MENU_CALLBACK ensures it doesn't get added to menu's etc. It just ensures Drupal is ready to process it.

Hope this helps.

/**
 * Implements hook_menu().
 */
function menu_magic_menu() {
  $items = array();

  /**
   * This is a simple callback.
   *
   * This will create a path at http://example.com/magic. When visited, that
   * URL will trigger the "menu_magic_page" function.
   */

  $items['magic'] = array(
    'title' => 'Menu Magic!',
    'page callback' => 'menu_magic_page',
    'type' => MENU_CALLBACK,
  );


/**
 * Page callback for 'magic'. This is the function that will get called
 * everytime a user visits http://example.com/magic.
 */
function menu_magic_page() {
  global $user;
  return t('Hello, @username!', array('@username' => $user->name));
}
  • I am using this in ajax $.ajax({ url: 'magic', type: "GET", success: function (data) { //Do something here with the "data" alert(data); } }); which is actuly returning me the HTML in alert rather the user name being return by this functions. What am I doing wrong? – Tanvir Ahmad Feb 2 '16 at 6:39
  • Rather I see RETURN is not working in 'menu_magic_page' but print. – Tanvir Ahmad Feb 2 '16 at 7:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.