Calling a module function from jQuery and Ajax
To answer to The second block of JS code is a test I am trying to do to call the ajax_username function of ajax_example.module. you wrote in your comment, what you can use in JavaScript code like $.ajax({url: 'ajax_username'}) as url is a route exposed in the hook_menu() implementation of a module, or the path of a PHP file. It isn't the name of a PHP function implemented from a module, nor the name of a file containing Javascript code (without the .js extension).

As concrete example of what Drupal core modules do, see the content of the statistics.js file.

(function ($) {
  $(document).ready(function() {
    $.ajax({
      type: "POST",
      cache: false,
      url: Drupal.settings.statistics.url,
      data: Drupal.settings.statistics.data
    });
  });
})(jQuery);


What $.ajax() gets as url is Drupal.settings.statistics.url, set from statistics_node_view() with the following code.

$settings = array('data' =&gt; array('nid' =&gt; $node-&gt;nid), 'url' =&gt; url(drupal_get_path('module', 'statistics') . '/statistics.php'));


In the test site I am using, the output of url(drupal_get_path('module', 'statistics') . '/statistics.php') is /modules/statistics/statistics.php.

So, if you want to call the callback associated to your ajax_username menu, you need to use $.ajax({url: '/ajax_username'}) or $.ajax({url: '/index.php?q=ajax_username'}), but in both the cases, the module must be installed and enabled.

If you don't want to enable a module for that, you cannot use hook_menu(), but you could create a PHP file containing the code to use, in the same way the Statistics module does with its statistics.php file.
Be warned: Use this only if you know exactly what you are doing, as using the wrong code could be a security risk for your site and its data.

I would rather use hook_menu().