0

I have a javascript file that doing encoding for some string and implement it inside foreach PHP function to get values but unfortunately javascript holding and storing the first value from the foreach function only and keep repeating it

PHP

foreach ($json_content as $index => $array) {
        echo '<textarea id="index" style="display:none">'.$index.'</textarea>';
        echo '<textarea id="encoded'.$index.'" style="display:none">'.$aa_encode.'</textarea>';
        echo '<script type="text/javascript" src="decdoe.js"></script>';
        echo '<script type="text/javascript">function();</script>';
}

Javascript

var index    = document.getElementById("index");
var AEncoded = document.getElementById("encoded"+index.value);
document.write(index.value);
document.write(function(AEncoded.value));

Output

000
firstvalue/firstvalue/firstvalue

What I missed?

10
  • ID should be unique in the HTML. You have it set so you have multiple called "index", chances are, the JS only ever notes the first one it sees. Commented Jul 14, 2020 at 22:35
  • It is unique, that's why I added $index beside the ID Commented Jul 14, 2020 at 22:36
  • id="index" is not unique. It's duplicated. Commented Jul 14, 2020 at 22:37
  • You are correct, I changed it to id="index'.$index.'" but it gave me this error Uncaught TypeError: index is null in console log Commented Jul 14, 2020 at 22:42
  • How to pass/send the index number to javascript file? Commented Jul 14, 2020 at 22:42

2 Answers 2

1

Here is the solution

First: I added the ID inside a loop in the Javascript file like this

var i;
for (i = 0; i < $numberofloops ; i++) {
   var AEncoded = document.getElementById("encoded"+[i]);
}

Then pulled out the function call from the foreach PHP

foreach ($json_content as $index => $array) {
        rest of code here
}
echo '<script type="text/javascript">function();</script>';
Sign up to request clarification or add additional context in comments.

Comments

0

if all you need to do is store every $index into a textarea and save it into a java var, then try throwing a while look on every case of echo that you need all variables from... so for example, you would put a code like this:

 while($index = value){
 echo $index
 }

inside of your #index textarea then grab that textarea's value with java

1 Comment

I did it but now the PHP print the output 3 times in each echo firstvalue/secondvalue/thirdvalue firstvalue/secondvalue/thirdvalue firstvalue/secondvalue/thirdvalue

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.