Search code examples
javascriptphpjqueryhtmldrupal-7

Passing information to JS File from Module File in Drupal 7


In one of my webpage I print one button multiple times and all have different logId. I want that when user click then there will JQuery into the picture and there should be no server side post-back. Since a unique log id is associated with every button so I pass the information to JS file from *.Module as below when the button is clicked:-

*.module File -- PHP File

$thm_button .= '<input type="button" class="clsPrevious" id="btnPrev_'.$user->uid.'_'.$logid;>';

*.js File

$('.clsPrevious', context).click(function (event) {
   var previousLog=this.id.split('_');

   //Retrieve log Id and Process the log id using AJAX call
}

This is working fine here but I feel there is security concern as everyone can view the log id of the button in HTML source.

Are there any ways in Drupal/PHP/HTML to pass the sensitive information to JS without showing in HTML Viewer.


Solution

  • You can pass values from PHP to Javascript with "Drupal.settings".

    Read more about it here.

    You can create a input button which looks something like this.

    $thm_button .= '<input type="button" class="clsPrevious" data-myModule=" . $key . ">;

    where $key is a random/serial variable but is unique per Log ID.

    Create a mapping array of key value pair and pass to javasript using drupal_add_js()

    <?php
      drupal_add_js(array('myModule' => array('_YOUR_CUSTOM_KEY_1_' => '_LOG_ID_1_')), 'setting');
    ?>
    

    And now modify your click function to,

    $('.clsPrevious', context).click(function (event) {
    
      var key = $(this).attr("data-myModule");
    
      // Now a this point you have the lookup table in Drupal.settings.myModule
      // use the "key" variable to find the LOG ID
    }