0

I am still new, so please forgive me if this question is too trivial or the issue has already been discussed. I didnt find anything specific, which led me to open a new question. That said, here is how it goes:

Im passing values from my database into data-attributes in order to use them in javascript to alter the width of certain elements (i.e. graphs). The element that should be altered according to the retrieved value is a p-Tag (together with others it sits inside a foreach):

<span class="fdpg-nut-vline"><p class="fdpg-nut-graph" id="graph" data-somedat="<?php echo "'" . $value['Nu_Val'] . "%'" ?>"></p></span>

The value of the data-attribute with the name "somedat" I want to use in js, like so:

var somevar = document.getElementById('graph').getAttribute("data-somedat");
document.getElementById("graph").style.width = somevar;

What I did?

  • I checked whether the format of the value is right. I therefore set a 'static' variable var somevartest = '20%'; and used it in the code above. It worked and the graph changed accordingly.
  • I checked if the value is passed into the data-attribute: (1) in the sourcode (its there!) and afterwards included an alert which shows me the value in the right format aswell (i.e. 'x%').

What is it that Im not getting? How can I solve my problem?

a2k
  • 15
  • 5
  • try `data-somedat="= htmlentities($value['Nu_Val']).'%' ?>"` – Lawrence Cherone Jul 12 '22 at 16:00
  • 1
    If that `...` is inside a `foreach` you'll have multiple elements with `id="graph"` - which is invalid, `id`s must be unique – brombeer Jul 12 '22 at 16:03
  • @brombeer You are right! I forgot to mention, that within the foreach I use an if-statement to check for a specific key-value pair within the array. – a2k Jul 12 '22 at 16:13

1 Answers1

0

The proper way to pass data from PHP to JavaScript is using a JSON string.

PHP:

<?php
$arr = get_from_database_as_array(...);

// at end of page before your scripts:
echo "<script>";
echo "var data = " . json_encode($arr, true) . ";";
echo "</script>";

HTML:

<script>
  console.log(data); 
  document.getElementById("elem1").style.width = data["elem1"] + "px";
  document.getElementById("elem2").style.width = data["elem2"] + "px";
  // and so on.
</script>

IT goldman
  • 14,885
  • 2
  • 14
  • 28
  • I managed to get it to work for me. THX! Although in my specific case I had to tweek it a little [https://stackoverflow.com/questions/12462318/find-a-value-in-an-array-of-objects-in-javascript]. So this is the working answer! Shout out to @LawrenceCherone for the handy solution nonetheless. – a2k Jul 15 '22 at 12:45