0

I have build a dynamic list from an array and must print the onclick event inline, I don't know of anyway other way to do this.

<?php

$dataArray = $_POST['dataArray']; // This is a valid array

ECHO '<div id="colorSelectorBox">';

for ($btn = 0; $btn < sizeof($dataArray); $btn++){
    ECHO '<div class="btn-group">
              <button onclick="buildGroupList("'.$dataArray.'")">' .$dataArray[$btn].'</button>
              <button><div ..Stuff..></div></button>
          </div><br>'; 
}
ECHO '</div>';

?>  

The problem is that the JavaScript function buildGroupList() does not receive an array from this instead the line looks like this in my developer tool:

onclick="buildGroupList(Array)"

How can I pass in an array of values through to JavaScript?

OR

How can I re-write this so that the call is not inline?

1
  • I don't understand. Where would that go? Commented Aug 20, 2015 at 21:42

2 Answers 2

3

The shortest answer is: use json_encode() which will convert the array to a json string, but it's not good practice anyway.

Sign up to request clarification or add additional context in comments.

1 Comment

I'm having a hard time converting the result into an array once it's in JS
2

Because you are trying to print the array as if automagically transforms itself into javascript array, that is, a string of its values separated by a comma (that is what it needs to output to the html, something the browser understands).

For that you need implode:

string implode ( string $glue , array $pieces )

Join array elements with a $glue string.

ECHO "<div class=\"btn-group\">
    <button onclick=\"buildGroupList(['".implode("','",$dataArray)."'])\">" .$dataArray[$btn]."</button>
         <button><div ..Stuff..></div></button>
    </div><br>";

It takes every element in the array and puts $glue string between every one of them. The end result looks like this:

//let's assume this is your array in PHP
<?php
    $dataArray = array('one','two','three');
?>

<!-- then your HTML looks like this -->
<button onclick="buildGroupList(['one','two','three'])">...</button>

Remember that PHP and Javascript don't know each other.

3 Comments

Didn't work. The JavaScript function takes an array as its parameter, not a list of comma separated strings.
Thanks, I'm still having trouble but this might be an issue with the single and double quotes
use double quotes in PHP so you can escape the ones needed in the HTML with a "\" as i did above, the "\" won't show in the HTML.

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.