Calling PHP function from JQuery in Drupal

Its not the default behaviour of the JQuery to call a PHP function directly, but this can be done calling a page cotaining PHP funtion in it.

But here is how to do it in DRUPAL.

We can use hook_menu to do this magic. Value in 'page callback' will be used as call back function in jquery.

function nodeex_glue_menu() {
  $items = array();
  /**
   * This is a simple callback.
   *
   * This will create a path at http://example.com/callme. When visited, that
   * URL will trigger the "_callme_ajax_page" function.
   */
  $items['callme'] = array(
    'title' => 'Callme Ajax!',
    'page callback' => '_callme_ajax_page',
    'type' => MENU_CALLBACK,
    'access arguments' => array('access content'),
  );
  return $items;
}
function _callme_ajax_page() {
  global $user;
  print $user->name;
}

When callme is called in JQuery, it is actuly trigerring the '_callme_ajax_page' funcition.

$.ajax({
  url: 'callme',
    success: function (data) {
    //Do something here with the "data"
    alert(data);
  }
});