Skip to content
Advertisement

Can’t call JavaScript function from PHP using a string as a parameter

I am using a PHP script to get data from a MySQL server. Once I get that data, I’m looping through it (still in PHP) and using it to output a series of datasets each with their own button

        $returnString = '<form action="/iOS/action_page.php" method="post">';
        
        // output data of each row
        while($row = $result->fetch_assoc()) {
            
            $echoString = '<h2>Study Title: '. $row['title'] . '</h2>';
            
            $echoString .= '<h3>Study Nickname: ' . $row['nickname'] .'</h3>';
            
            $echoString .= '<button type="button" id="login-button" Onclick="setUrl(' . rawurlencode($row['title']) . ')"> View Tasks </button>';
                            
            echo $echoString;
        }

(The “title” of the row is a string that may or may not have spaces and such, like “Hello%20World”)

The ‘setUrl’ function sits outside of the PHP brackets and just tries to move to a new page:

        <script>
          function setUrl(tableTitle) {
              window.location.href = "https://exampleWebsite.com/PHPPage.php?id=".concat(tableTitle);
          };

       </script>

But every time I try to click a button, I get this error popping up in the console:

SyntaxError: No identifiers allowed directly after numeric literal

The only way I can get it to work is by passing in an Integer rather than a string, but that doesn’t work for my use case.

Advertisement

Answer

Mixing three different languages on a single line of code drastically increases the chances of string quoting errors. Consider what this line of code outputs:

$echoString .= '<button type="button" id="login-button" Onclick="setUrl(' . rawurlencode($row['title']) . ')"> View Tasks </button>';

If the “title” value is a string, the resulting button is:

<button type="button" id="login-button" Onclick="setUrl(some string)"> View Tasks </button>

Which means the JavaScript you’re trying to execute is:

setUrl(some string)

Which is invalid because strings need to have quotes around them.

The quickest approach is to simply add those quotes:

$echoString .= '<button type="button" id="login-button" Onclick="setUrl('' . rawurlencode($row['title']) . '')"> View Tasks </button>';

A more sustainable solution would be to separate your JavaScript from your HTML entirely. Output just the button with the “title” as a data attribute:

$echoString .= '<button type="button" id="login-button" data-title="' . rawurlencode($row['title']) . '"> View Tasks </button>';

Then in separate JavaScript (either on the page itself or linked from a .js file), bind the click handler:

document.querySelector('#login-button').addEventListener('click', function () {
  setUrl(this.getAttribute('data-title'));
});
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement