Wednesday, January 27, 2016

Drupal 7: Calling Session Variable with Javascript


Step 1: Prepare hook menu to call getSession function. Return the $result variable after this line $result = $_SESSION['_custom_variables'];

sites/all/modules/custom/mymodule/mymodule.module


/** Comment **/ 
/**
 * Implements hook_menu().
 */
function mymodule_menu() {
  // track url
  $items['getSession'] = array(
    'page callback'    => 'mymodule_getSession_ajax',
    'access callback' => TRUE
  );

  return $items;
}

/**
 * Called by ajax request to getSession
 */
function mymodule_getSession_ajax() {
  if(isset($_POST['action'])) {
    $action = $_POST['action'];
    unset($_POST['action']);
  }
  else {
    $action = 'default';
  }

  mymodule_getSession('ajax', $action, $_POST);
}

/**
 *
 * @param string $type ajax|server This informs the function if it should use the current request or REFERER as the url
 * @param string $action action to send
 * @param array $vars Associative array of variables to send as custom vars
 */
function mymodule_getSession($type, $action, $vars=array()){
  $url = $_SERVER['HTTP_REFERER'];
  $params = parse_url($url);

  $result = array();

  $customVariable = ['MemberID', 'EmailID', 'SpecialtyID'];

  if(isset($params['query'])){
    parse_str($params['query'], $query);

    foreach ($query as $key => $value) {
      if(in_array($key, $customVariable))
      {
        $_SESSION['_custom_variables'][$key] = $value;
      }
    }
  }
  $result = $_SESSION['_custom_variables'];

  print drupal_json_output($result);
  exit();
}




Step 2: Call hook menu with ajax, return the result after success call.

sites/all/themes/mytheme/js/mytheme.js


/** Comment **/ 
(function ($) {
jQuery(document).ready(function() {
  var mysession = getSession(); 

  console.log(mysession);

/*
   * Get Session Function
   * @action is the name of the page
   * @actionType is either 'page_view' or 'link'
   */
  function getSession() {
    // add action and action type
    var data = {action:'custom_variables'};
    var basePath = '';
    var result;
    if ( (Drupal.settings.basePath != undefined) && (Drupal.settings.basePath != '/') ) {
      basePath = Drupal.settings.basePath;
    }
    basePath = basePath + '/getSession';
    basePath = basePath.replace('//', '/');
    jQuery.ajax({
      url: basePath,
      type:'POST',
      dataType:'json',
      data:data,
      async:(jQuery.browser.safari || jQuery.browser.mozilla) ? false : true,
      success: function(data) {
        // for this current implementation, there is no need for action upon success
        result = data;
        },
      error: function(xhr, status, error) {
        // error
      }
    });
    return result;
  }
})
}
)(jQuery);



No comments:

Post a Comment