Artifacts Gallery Guilds Search Wiki Login Register

Welcome, Guest. Please login or register. - Thinking of joining?
Autumn, 20 Nov 2026 - @35.34
Forum Activity: Four Stars Random | Recent Posts | Guild Recents
News: :sleep: These are fast times on the World Wide Web~ Guild Events: Noir-vember TTRPG game jam
+  MelonLand Forum
|-+  Da Web Revival
| |-+  ✁ ∙ Web Crafting
| | |-+  ♺ ∙ Snippets & Materials
| | | |-+  Passing PHP variable to javascript


« previous next »
Pages: [1] Print Embed
Author Topic: Passing PHP variable to javascript  (Read 83 times)
Noah_S
Sr. Member ⚓︎
****
View Profile WWWArt


Noah. Earth. I make website. I.. I.. Noah. Earth.
⛺︎ My Room
iMood: Noah_S
RSS: RSS

Guild Memberships:
Artifacts:
Caught by RubbereonfunguyVisited on Melon's 10th Anniversary!I got robbed by Dan Q on Melonland!I met Dan Q on Melonland!A coin!
« on: Autumn, 17 Nov 2026 @644 » Toggle Font Embed

I was experimenting in the w3schools try it editor, and found how to pass a PHP variable into javascript. In case anyone, including future me, needs it, here's a snippet of code that returns

Quote
Volvo

Code
<!DOCTYPE html>
<html>
<body>
<p id = "test"></p>
<?php
$cars = "Volvo";
?>
<script>
let text = <?php echo json_encode($cars); ?>;
document.getElementById("test").innerHTML = text;
</script>
</body>
</html>

For those not fluent in PHP, "echo" is PHP for "please display the following". $variable-name is how you declare a variable.

Logged

perfectionist_better.gifweb_designer.gifspeed_of_time.gifbutton290.pngmy_dream_wedding.gifClippy beats AI

Artifact Swap: Clippy just wanted to helpClippy would never track youClippy didn't need data centersClippy would never make a subscription programClippy would never sell your dataFake penguinLarge watercraftGrowing ballwhen life gives you crab make mailnonbinary yappin kittayyMessage Buddylaptop
Dan Q
Hero Member ⚓︎
*****
View Profile WWWArt


I have no idea what I am doing
⛺︎ My Room
RSS: RSS

Guild Memberships:
Artifacts:
Caught by RubbereonThe Worm is creeping around Melonland profiles!Dan Q Cruisin'I DIDN'T meet Dan Q on Melonland!Visited on Melon's 10th Anniversary!
« Reply #1 on: Autumn, 17 Nov 2026 @666 » Toggle Font Embed

A few other options I've used -

Option 2: Big JSON dump

This one's great if you've got a LOT of data, and/or you load it in a variety of different ways e.g. also by fetch requests. It can be used to dump any arbitrary PHP object (including arrays etc.) into a special block, and then the JS code can extract it later:


Code
<script type="application/json" id="my-data">
/* Here the PHP code converts the object to JSON: */
<?php echo json_encode( $any_php_object ); ?>;
</script>

<script>
/* Here's the JS code that loads the JSON: */
const myData = JSON.parse(document.getElementById('my-data').innerText));
</script>

Option 3: data- attributes

Another approach that I like to use is data- attributes. This approach is especially good where HTML elements "represent" something that is also referred to in PHP. For example, suppose in PHP I maintain an array of photos, where each has an ID (number) and URL. I want to display the photo, but I also want the ID available to JavaScript so that I can later do something clever with it (e.g. enabling the user to drag their favourite pictures into a box which then get converted into numbers in a hidden field, ready for submission of their votes back to the server):


Code
<ul class="pictures">
  <?php foreach( $pictures as $picture ) { ?>
    <li data-picture-id="<?php echo $picture['id']; ?>">
      <img src="<?php echo $picture['url']; ?>">
    </li>
  <?php } ?>
</ul>

<script>
/* For now, let's just handle clicking on a picture and SHOW the ID number.
 * In reality we'd probably want to do something cleverer! */
document.querySelector('.pictures').addEventListener('click', function(e){
  // Get the <li> we clicked on:
  const li = e.target.closest('li');
  if(!li) return; // If we somehow didn't click on an <li> but the <ul> itself!

  const pictureId = li.dataset.pictureId; // .dataset.pictureId means the data-picture-id attribute!
  alert(`You clicked picture with ID: ${pictureId}.`);
}, { capture: true });
</script>

There are plenty more options besides! Just remember that anything you put into HTML/JS can be read by the user and isn't secret! So don't send anything from PHP to JS that you wouldn't be happy showing your visitor!

(And if you're outputting anything "untrusted", e.g. things that a user typed into your guestbook, ensure it's suitably escaped!)

Logged

https://danq.me/_q26t/badges/dan-q-88x31-lighter.gif https://danq.me/_q26t/badges/dan-q-88x31-peekaboo-scroller.gif https://beige-buttons.danq.dev/beige-buttons-88x31.gif https://embed-html.danq.dev/embed-html-88x31.gif https://origami.danq.dev/88x31.gif https://skelly.monster/dem-bones-88x31.gif

Artifact Swap: Pink ham-ham rangerPolyamorousI met Dan Q on Melonland!shoeJoined 2025!cinnamoroll
Pages: [1] Print Embed 
« previous next »
 

Melonking.Net © Always and ever was! SMF © 2021 | Privacy Notice | Send Feedback | Supporters ♥ Guide | Rules | Whos a Mod? | RSS | WAP | Mobile


MelonLand Badges and Other Melon Sites!

MelonLand Project! Visit the MelonLand Forum! Support the Forum
Visit Melonking.Net! Visit the Gif Gallery! Pixel Sea TamaNOTchi
@000 Melon
Land
Forum Art Hub Chat Webring Explore Random Recent Tenement Arcade Want to Login or Join ? Web Craft Guide Graphic Catalogue Wiki Help I'm Lost! Link Land Newsletters Image Stream Minecraft: Online
Zap!
Passport Sites tamaNOTchi Asatte Add your site?
Aero Archive Onio Cafe 32 Bit Cafe Status Cafe