Skip to main content
Drupal 8

Main navigation

  • Home
    • Question And Answer
    • NEWS
    • Projects
  • Tutorials - Drupal
    • Android
    • Other
User account menu
  • Log in

Breadcrumb

  1. Home

JavaScript useful tips and examples

By editor , 23 January, 2018
Question

How to get HTTP Header information on client side using java script ?
How to get query parameters from JS like $_GET on php ?
How to Check if Function, method or Class Exists ?

Get HTTP Header information From JavaScript

Note : It's not possible to read the current headers. You could make another request to the same URL and read its headers, but there is no guarantee that the headers are exactly equal to the current.

Example:
var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
//var headers = req.getAllResponseHeaders().toLowerCase();
var headers = req.getAllResponseHeaders();
//
// Get a particular header (Hear : Cache-Control).
headers = headers.split("\r\n");
headers.forEach(function (entry) {
    if (entry.indexOf("Cache-Control") !== -1) {
        console.log(entry.split(":")[1].trim());
    }
});

Note : Most of common informations are available under 'navigator' which does not need a second request. try : console.log(navigator);


Get Query String Parameters with JavaScript

The RAW data is available from  window.location.search , This gives everything after the '?'.
Try console.log(window.location.search);

Get a particular parameter.
Example : (Hear "?post=1234&action=edit")
var urlParams = new URLSearchParams(window.location.search);
if (urlParams.has('post')) {
var postValue = urlParams.get('post');
}

And provide different functions :
var urlParams = new URLSearchParams(window.location.search);
console.log(urlParams.has('post')); // true
console.log(urlParams.get('action')); // "edit"
console.log(urlParams.getAll('action')); // ["edit"]
console.log(urlParams.toString()); // "?post=1234&action=edit"
console.log(urlParams.append('active', '1')); // "?post=1234&action=edit&active=1"

Note : URLSearchParams is not supported by old web browsers.
Check the compatibility : https://caniuse.com/#feat=urlsearchparams

You can also do like:
function getUrlParameter(name) {
    name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
    var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
    var results = regex.exec(location.search);
    return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
getUrlParameter('post'); // "1234"
getUrlParameter('action'); // "edit"

 


Check if Function, method or Class Exists Before Calling


//Example 1:
if (typeof yourFunctionName == 'function') {
  yourFunctionName();
}
//
//Example 2:
if (typeof URLSearchParams == 'function') {
  var urlParams = new URLSearchParams(window.location.search);
}
//
//Example 3 : If function not exist
if (typeof URLSearchParamsError == 'undefined') {
  console.log("This class not available");
}

 

 

Tags

  • JavaScript
  • Code
Add JavaScript to a module
Run JavaScript code via web browser console.

Comments

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.

Links

  • Drupal.org
  • Drupal core release cycle
  • Drupal events with ease
  • Unit test with Drupal using PHPUnit (Drupal 10)
  • Tokens for file upload url
  • Tips for Docker
  • CKEditor inline image files usage for custom forms.
  • Install Docker on Linux Mint
  • Install PHP 8.1
  • Drupal Security Best Practices
  • Order and sort items with tabledrag
  • Add a custom service YAML container
  • Apply a patch with composer