How to call function from PHP file (or another module) in JS file from my custom module? After this question, I try to write custom module to add support Views Infinite Scroll to Background Images module. Here is my code:

my_module.module


/**
 * @file
 * Module file for Background Image for Views Infinite Scroll.
 */

/**
 * Implements hook_page_build().
 */

function my_module_page_build() {
  // Settings.
  drupal_add_js(array(
    'viewClass' =&gt; '.view-content',
    'nodeClass' =&gt; '.node-content',
  ), 'setting');
  // Add JS to page.
  drupal_add_js(drupal_get_path('module', 'my_module') . '/js/my_module.js');
}

/**
 * My function.
 */

function my_module_function() {
   // Code here
}


And ./js/my_module.js

/**
 * @file
 * This is main script of Background Image for Views Infinite Scroll.
 */

(function($, Drupal) {

  Drupal.behaviors.my_module = {
    attach: function (context, settings) {
      $(Drupal.settings.viewClass).on('DOMNodeInserted', function() {
        // Code here
      });
    }
  }

})(jQuery, Drupal);


How call function my_module_function() in my JS file?
You can add a menu callback in your module, that will be used by JS to send-receive values from PHP.

/**
 * Implements hook_menu().
 */
function my_module_menu() {
  $items = array();
  $items['my-module/my-function'] = array(
    'title' =&gt; 'Ajax callback for my function.',
    'page callback' =&gt; 'my_module_function',
    'access arguments' =&gt; array('access content'),
    'type' =&gt; MENU_CALLBACK,
  );
  return $items;
}

function my_module_function() {
  // Remember you have to print your results if you want to
  // send any values back to JS.
  print 'Hi, there!';
  drupal_exit();
}


Now in your JS code, you make an Ajax call and, optionally, get values back from PHP (if desired).

$.ajax({
  url: Drupal.settings.basePath + "?q=my-module/my-function",
  done: function(data) {
    // If my_module_function returns any value, it will come in the data variable.
    alert(data);
  }
});