0

I'm trying to pass a PHP array to a button's onClick function as a parameter. A single array index works, however, passing the entire array triggers an error which states that an invalid character has been found. I've tried using json_encode on the array and then parsing it into a javascript variable in the onclick function. It still doesn't work. I get the following error when I click the button: Uncaught SyntaxError: Invalid or unexpected token.

This works fine:

onClick="saveimg('<?php $urls = array(); $urls = $chart->getUrls(); echo $urls[0]; ?>')"

But this doesn't:

onClick="saveimg('<?php $urls = array(); $urls = $chart->getUrls(); echo json_encode($urls); ?>')"

Here is the saveimg function:

    function saveimg(urls)
    {
        var l = JSON.parse(urls);
        alert(l[0]);
    }
  • By _this doesn't_ what do you mean exactly? can you check your console for errors – Spoody Apr 09 '18 at 18:53
  • this might help: https://stackoverflow.com/questions/5618925/convert-php-array-to-javascript – keaton Apr 09 '18 at 18:54
  • @MehdiBounya I already stated this in the question. Please read it carefully. Uncaught SyntaxError: Invalid or unexpected token. – Douglas Northwell Apr 09 '18 at 18:56
  • Check your page source and post the line where you have the `onClick` attribute – Spoody Apr 09 '18 at 18:57
  • It shows the correct array contents: onClick="saveimg('["https:\/\/lastfm-img2.akamaized.net\/i\/u\/174s\/9a04325d217543c4a5fe54e4e238ecad.png","","","","","","","",""]')" – Douglas Northwell Apr 09 '18 at 18:58
  • That's hardly correct `onClick="saveimg('["` that's a complete quote block, or matched pair of quotes, if you like. – ArtisticPhoenix Apr 09 '18 at 19:01
  • 1
    You are missing a htmlspecialchars call: htmlspecialchars(json_encode($urls)). You must escape all output for the context it's used in. In this case JavaScript embedded in HTML, so you have to escape for JavaScript first (json_encode), and then for HTML (htmlspecialchars). – Peter Apr 09 '18 at 19:02
  • @Peter that was it! Thanks – Douglas Northwell Apr 09 '18 at 19:04
  • Consider using a template engine that does this automatically. I like [Twig](https://twig.symfony.com). – Peter Apr 09 '18 at 19:08

0 Answers0