Igor Simic
4 years ago

Load Javascript by Ajax call and execute it in Drupal


How to load JavaScript by using Ajax call and execute it in Drupal? Sometimes we need to load JS file for specific users (for example restricted by IP, country ...) and here is how we can load it by using Ajax call and PHP on other side.

Let's say that we have a Drupal module which should make this service. So First we have to create function inside this module and create a route to that function:

 function my_module_menu() {

    $items = array();
    // cretae a route to the method
    $items['my_module/get_js'] = array(
         // define method name
         'page callback' => 'my_module_ajax_call',

         'access arguments' => array('access content'),

         'type' => MENU_CALLBACK,
    );

  return $items;
}

and now we will create that function:
function my_module_ajax_call(){

  // get the user IP
  $ip_array=explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);

    // white list
    $IPwhitelist = array('192.168.1.1');

    // get last one from array - last one should be the valid one added by load balancer
    $ip_array=explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); 
    $ip=trim($ip_array[count($ip_array) - 1]);

    if(in_array($ip, $IPwhitelist)){

      $load_JS = "console.log('Java script code goes here....')";

      echo $hidden_autofill_JS;
      
    }else{

      echo "console.log('Show this if IP is not on white list')";
      
    } 
  
  
}
So as you can see in this function we are having IP restriction, and only whitelisted IPs will load correct JS.

And the last part is to call drupal method from JS:

// call script
    $.getScript( "/my_module/get_js", function( data, textStatus, jqxhr ) {});