简体   繁体   中英

calling javascript function from PHP - quotes issue

I'm trying to call javascript function from PHP. the idea is to create each parameter from file as link that when clicked inputs it's value into text box.

$lines = file('http://localhost/repositories.txt');
foreach ($lines as $line_num => $line) {
    echo  "<a onclick='javascript:(document.folderForm.folderLocation.value=".htmlspecialchars($line) .");' href='#'>".htmlspecialchars($line) . "</a><br />";
}

when clicking the created links I'm getting (for example):

ReferenceError: test2 is not defined

I think there should be quotation marks around the parameter, but I can't add them. I tried to use ' \\" ' without success. any ideas?

You need to quote and properly escape the JavaScript string that you're assigning to the input value property. You can use json_encode for that:

echo "<a onclick='document.folderForm.folderLocation.value=".htmlspecialchars(json_encode($line)) .";' href='#'>".htmlspecialchars($line) . "</a><br />";

Demo


The main cause of the issue is that your code was missing the quotes around the string value, so JavaScript was interpreting it as an identifier (variable name).

json_encode adds quotes around the value and, more importantly, escapes the value to make sure it is a valid JSON string (it escapes line feeds, carriage returns and quotes which could easily result in a syntax error otherwise).

JSON is a subset of the JavaScript syntax, so any valid JSON is valid JavaScript. (provided it is used in a suitable context)

Finally, as the value is inside an HTML attribute, htmlspecialchars is still applied to escape the value. It escapes quotes to make sure the variable value does not break out of the attribute value and also escapes characters such as & to not be interpreted as the beginning of an HTML entity sequence.


Finally, I would recommend against echo in this case, as to reduce the number of quotes and make interpolation easier to read:

$lines = file('http://localhost/repositories.txt');
foreach ($lines as $line_num => $line) { ?>
    <a onclick='document.folderForm.folderLocation.value=<?= htmlspecialchars(json_encode($line)) ?>;' href='#'><?= htmlspecialchars($line) ?></a><br />
<?php } ?>

Demo

Note: PHP short echo tags are available everywhere independent of configuration as of PHP 5.4. Switch <?= to <?php echo if you need to support PHP < 5.4.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM