Skip to main content

How to pass the base url to drupalSettings for global access

/**
 * Implements hook_page_attachments_alter().
 *
 * @inheritdoc
 */
function your_theme_page_attachments_alter(&$page) {
  global $base_url;
  $page['#attached']['drupalSettings']['baseURL'] = $base_url;
}

Then in your custom theme js file

/**
 * @file
 * Detection of a user location or and sending location data to the server with ajax request.
 */

(function ($, Drupal, drupalSettings) {

  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function (position) {
      // JSON.stringify can incorrect serialize objects returned by navigator.getCurrentPosition
      // @see http://www.allannienhuis.com/archives/2015/02/04/beware-json-stringify/
      // Therefore we need to copy the object's properties into plain javascript object.
      var coords = {
        lat: position.coords.latitude,
        long: position.coords.longitude
      };
      // Send a location data to the server.
      $.ajax({
        url: drupalSettings.baseURL+'/user_location',
        dataType: 'json',
        type: 'post',
        contentType: 'application/json',
        data: JSON.stringify(coords),
        processData: false,
        success: function(data) {
          // For testing purpose, the server returning received data with response.
          console.log(data);
        }
      });
    });

  } else {
    alert("Sorry, your browser does not support HTML5 geolocation.");
  }

})(jQuery, Drupal);

 

theme