• 0

Declare a global variable I can use all over a website?


Question

Hey

I want to declare a variable that is global that I can use (and modify) all over my website.

It is a simple HTML textbox that I use when I click a "button" (it is designed to look like a button) and when I click it, I execute a Javascript function and that is where I also want to create/modify and store the variable which is the value in the HTML textbox

My main problem lies that Im trying to create a client side languge based (JS) global variable and then trying to access in server side language based (PHP) pages. I have to be able to access it from other JS, PHP, PHTML, HTML, etc. pages.

A cookie comes to mind but I tried "document.cookie" and it doesnt work; I suppose that it only applies to the CURRENT document at hand. The other option Ive read about is using Ajax but I have no idea how to do it and for ONE thing I perfer another solution almost :)

Thanks for all the help!

6 answers to this question

Recommended Posts

  • 0

Given the developments of EU Cookie Law (that will come in force May 26th this year; I believe UK has already even ratified it), I'll be using database storage for sessions, and I recommend databases, written/read using AJAX, in this case as well, even though it may be quite inefficient approach.

  • 0

2 points on cookies, potentially of relevance to the OP:

Does this only affect websites hosted in the EU?

The location of your hosting is irrelevant, but the location of your organisation is not. Your organisation must fall within the legal jurisdiction of the EU. Each member state has their own laws, which are based on the same EU directive, but may differ slightly.

For most small/medium organisations, being located in the EU will mean you must comply.

Are all cookies affected?

The vast majority are - all cookies that are not "strictly necessary for a service requested by a user".

The law allows an exception for "strictly necessary" cookies, such as those used to remember when something has been added to a shopping basket. These cookies would be expected by the user implicitly for the action they requested to be carried out. Another example would be login.

http://silktide.com/cookielaw

I.e. if the OP is outside the EU, or if the cookie is necessary, it's fine to use a cookie.

  • 0

I think I'll actually have to read that ebook they have there (or even the law itself, if available anywhere). It's all confusing, with those exceptions. Currently I'd rather remove functionality than have anything to do with it. :s

Although I'm not impartial to the problem EU wanted to address.

  • 0

Cookies are one solution, assuming the cookie is "essential to correct functioning of the website" (non-essential cookies for, say, tracking user movement or analytics, will require an opt-in message for EU users). They're pretty easy to use, and most, if not all people now, have them enabled. This'd be how I'd do it.

AJAX is another option. You'd store the "global variable" as a session variable, and then create an AJAX function to request the variable's value from a PHP page, which will then be returned in the AJAX response. This however is extremely slow compared to the cookie method, as it requires a full round trip to the server. It also requires that the user have JS enabled, and if the variable value is required for the site to work correctly, users with JS disabled are going to have a bad time.

=====

With regards to the EU cookies law, not all cookies are covered. Cookies that are essential to the running of the site (i.e. if the user doesn't opt-in, the site will be FUBAR) are allowed without having to prompt the user, however non-essential cookies (tracking cookies, analytics, theming, etc) will require an opt-in message to appear for the user. Being outside the EU isn't a "get out of jail free" card either. Any website any EU visitors must have it enabled (it's where the user lives, not where you live, that matters).

  • 0

This law does not affect me in any way shape or form.

This is basically what Ive done/tried so far:

For cookies creation in JS I based myself off http://www.w3schools.com/js/js_cookies.asp

In my Javascript:

document.cookie="textname=" + document.getElementById('textname').value;

With my textbox being declared as (HTML):

<input type="text" id="textname" name="textname"/>

I KNOW this works because right after that document.cookie line I put

alert(textname);

And it showed me the value correctly....

Now on to a completely different PHP page (PHTML to be exact):

/*random stuff*/
<?php
session_start();
?>
/*more HTML PHP etc..........*/
<?php echo $_COOKIE["textname"];  ?>

And it simply shows blank. Nothing else.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Exactly. They won't go 100 because current gen consoles are simply too old for any groundbreaking graphics or gaming experience otherwise. They will go with standard (console) price 70 or go with 80 if they really want to go premium. Of course they will have more expensive options too with some useless cosmetics as always.
    • Doesn’t surprise me at all. God is light & He gave us life so it sounds almost logical that we would therefore emit a certain amount of light.
    • This is what I want. Hey Gemini, how do I remove you from all my google products permanently?
    • I would never install install this build before rtm process. only 3 months to go. never install on your daily devices. just wait 3 months.
    • Motrix Next 3.9.6 by Razvan Serea Motrix Next is a modern, open-source cross-platform download manager built as the official next-generation successor to the original Motrix project. It has been completely rewritten using Tauri 2, Vue 3, TypeScript, and Rust, while still relying on the powerful Aria2 download engine for high-speed multi-protocol transfers. The app supports HTTP, HTTPS, FTP, BitTorrent, ED2K and magnet links, offering advanced features like multi-connection acceleration, task scheduling, bandwidth control, and batch download management. With a significantly reduced install size (around 20MB), it focuses on being lightweight, fast, and resource-efficient compared to traditional Electron-based download tools. Designed for Windows, macOS, and Linux, Motrix Next delivers a clean, modern UI inspired by Material Design 3 principles, with smooth animations and a minimal workflow. It improves usability through better download organization, system tray integration, and enhanced torrent handling including selective file downloads and tracker management. Motrix Next features: Multi-protocol downloads — HTTP, FTP, BitTorrent, Magnet, .torrent, ED2K, and Metalink tasks BitTorrent — Selective file download, DHT, peer exchange, encryption controls, metadata caching, GeoIP peer flags, and tracker probing Browser extension integration — Embedded Extension API with independent authentication, download confirmation, smart auto-submit, filename hints, referer/cookie forwarding, and real-time controls (Chrome Web Store · Edge Add-ons) Safe filename handling — Content-Disposition, RFC 2047, non-UTF-8, percent-encoded, and extensionless URL resolution with path traversal sanitization Download organization — Favorite and recent folders, optional file-type categorization, stale-record cleanup, and completed history backed by SQLite Concurrent downloads — Independent controls for active tasks, HTTP connections per server, segments per file, and BT peer limits Speed control — Global and per-task upload/download limits with day-of-week and time-of-day scheduling System integration — Tray operation, optional tray speed display, macOS Dock badge/progress, protocol handlers for magnet://, thunder://, and motrixnext:// Lightweight mode — Destroys the WebView on minimize-to-tray while Rust keeps the engine, task monitor, notifications, history, and extension routing alive Notifications and power options — Native task start/complete/failure notifications, keep-awake during downloads, and optional shutdown after completion Network controls — Scoped proxy support for downloads, app updates, and tracker updates, plus system proxy detection Auto-update channels — Stable, Beta, and Latest Across Channels policies with separate download and install phases Diagnostics — Structured logs, exportable diagnostic ZIPs, database integrity checks, automatic DB rebuild, and Linux GPU rendering fallback Personalization — Light/dark/system theme, 10 color schemes, 26 languages, and first-launch system language detection Motrix Next 3.9.6 changelog: New Features Clipboard management — App-owned copy actions no longer trigger the Add Task auto-detect popup. aria2 input compatibility — Multi-line aria2-style task input is supported for URLs with per-task options such as out=. BitTorrent IPv6 DHT — Added IPv6 DHT support and related configuration. File category URL patterns — File category rules can match URL patterns with validation and localized hints. Task status tags — Added clearer waiting and sharing states for task cards. Download event bridge — Added an aria2 WebSocket event bridge for faster download notifications. Improvements Improved task list transitions and preserved task state during tab switches. Kept RPC origin access enabled for local integrations. Restored AppImage stripping in release builds after beta validation. Added localized preference guidance across supported languages. Download: Motrix Next 64-bit | ARM64 | macOS ~20.0 MB (Open Source) Links: Website | macOS / Linux | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • Conversation Starter
      sumytbe earned a badge
      Conversation Starter
    • One Year In
      B4dM1k3 earned a badge
      One Year In
    • One Year In
      DarkWun earned a badge
      One Year In
    • Dedicated
      Almohandis earned a badge
      Dedicated
    • Dedicated
      JuvenileDelinquent earned a badge
      Dedicated
  • Popular Contributors

    1. 1
      +primortal
      508
    2. 2
      +Edouard
      181
    3. 3
      PsYcHoKiLLa
      86
    4. 4
      Michael Scrip
      78
    5. 5
      Steven P.
      75
  • Tell a friend

    Love Neowin? Tell a friend!