V
V
Vasily Petrov2018-02-07 02:30:51
PHP
Vasily Petrov, 2018-02-07 02:30:51

How to pass each value of a variable from a loop from php to js?

There is a php loop.
Every time the $var variable changes.
I "pass" it to js like this: So js gets only the value from the last run of the loop. How in js by clicking on element-1 to get var from element-1. By clicking on element-2, get the var variable from element-2, and so on?
<script>var var = "<?php echo $var; ?>";</script>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pavel, 2018-02-07
@mbpig

The simplest thing is to pass the array from php to js as json (const data = <?=json_encode($some_array);?>)
and work with it in js, for example:

var data = {'1': 'one data', '2': 'two data'}; //получившийся json из массива в php

$('button').click(function(){
  var id = $(this).attr('id');
  var value = data[id] ? data[id] : 'empty';
  alert(value);
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question