0

I declare php arrays, i fill them with strings taken from query. I have to pass this arrays to a handler of a element in the page. Handler can't read this arrays.

PHP:

    $names = $paths = $infos= [];
    $i = 0;
    while($row = $result->fetch_row())
    {
            $names[$i]= $row[0];
            $paths[$i]= $row[1];
            $infos[$i]= $row[2];
            $i++;
    } 
    ...
    for($i = 1; $i < ($length/8)+1  ; $i++)//arrotonda per eccesso
    {

        $jsNames = json_encode($names);
        $jsInfo  = json_encode($infos);
        $jsPaths = json_encode($paths);
        //echo $jsNames."<br>";
        //echo $jsInfo."<br>";
        //echo $jsPaths."<br>";
        ?>
        <a href="#" onClick="changePhoto(<?php echo $i.','.$jsNames.','.$jsInfo.','.$jsPaths ?>)" class="w3-bar-item w3-white w3-button"> <?php echo $i ?></a>

JS:

function changePhoto(num,names,paths,infos){
 //nothing
 }

Browser error: Uncaught SyntaxError: Unexpected token }

Opening browser debugger: (function(event){changePhoto(2,[ })

5
  • What return commented echoes? Commented Dec 27, 2017 at 11:43
  • can you pease update total code clearly Commented Dec 27, 2017 at 11:45
  • I bet you have a problem with quotes here. Your jsons will have " in it. So try to change onClick="..." to onClick='....' Commented Dec 27, 2017 at 11:46
  • Should the last } be a ] in (function(event){changePhoto(2,[ }) Commented Dec 27, 2017 at 11:49
  • but why are you including all the values anyway? You really need that?Or could you just make it echo $i.",'".$names[$i]."','".$infos[$i]."','".$paths[$i] Commented Dec 27, 2017 at 11:49

1 Answer 1

2

You will have a problem with quotes here. Your jsons will have some " in it, and your html-attribute is enclosed in ", too. So change

onClick="changePhoto(<?php echo $i.','.$jsNames.','.$jsInfo.','.$jsPaths ?>)"

to

onClick='changePhoto(<?php echo $i.','.$jsNames.','.$jsInfo.','.$jsPaths ?>)'
// note the single-quotes here!

Sidenote:
You should put these lines $jsNames = json_encode($names); outside the loop, as they won't change anymore. But now you're doing the same work several times.

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

Comments

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.