Pass Javascript Variable values to php with jQuery.cookie in Drupal 7

Oct
2014
14

Browscap module (https://www.drupal.org/project/browscap) is great when you want to have control on the layouts depending on the device that access your website. But what if you want more control? What if you care more for resolution rather than device? If for example you target desktop screens with smaller resolutions? Well then it's time for calling: jQuery.cookie in Drupal 7 to the rescue! Although it is not documented Drupal core includes the jQuery.cookie library. What jQuery.cookie does is that as a tiny library it helps us, managing cookies via javascript:

$.cookie('width_res', $(window).width()); // adds width resolution to our cookied
console.log($.cookie('width_res')); // => "our browser width"

All you need then in order to have access to this jquery cookie created variable within php is just to add the Jquery cookie library before you try to access the variable with $_COOKIE.

<?php
drupal_add_library
('system', 'jquery.cookie');
drupal_set_message('here is the Cookie var: '.$_COOKIE['width_res']);
?>

And you are ready.

this is an arrow pointing back to the top of the page