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

Latest Articles

Using drupal/core-composer-scaffold to prevent rewriting .htaccess or robots.txt file admin_pixelthi… Sun, 12/01/2024 - 16:49 Using drupal/core-composer-scaffold to prevent rewriting .htaccess or robots.txt file

Using drupal/core-composer-scaffold to prevent rewriting .htaccess or robots.txt file

composer
Controlling ckeditor styling options with hook_editor_js_settings_alter admin_pixelthi… Thu, 05/16/2024 - 10:49 Controlling ckeditor styling options with hook_editor_js_settings_alter

Controlling ckeditor styling options with hook_editor_js_settings_alter

php hook hook_editor_js_settings_alter hook_field_widget_single_[WIDGET_TYPE]_form_alter
Upgrading Drupal 9 Modules for Drupal 10: A Simple Guide admin_pixelthi… Tue, 09/05/2023 - 14:18 Upgrading Drupal 9 Modules for Drupal 10: A Simple Guide

Upgrading Drupal 9 Modules for Drupal 10: A Simple Guide

composer drupal9 drupal10