i’m trying to pass a php defined string with spaces to a javascript function, so that i can append to a query string. However, the function only works when there are NO spaces, and does not even execute when there are spaces — by testing with alert().
is there a way I can pass strings with spaces into javascript functions, so that i can eventually do an escape(), and then append to my query string? (using alert() in this example)
.php file
<a onClick=showUser('<?php echo $stringwithspaces; ?>')>click here</a>
.js file
function showUser(str)
{
alert (str);
}
if I could only do something like… onClick=showUser(escape('<?php echo $deptname; ?>'))… that would be awesome, but that didn’t work. Any help would be much appreciated! Thanks!
The problem is you didn’t quote the attribute value. You can leave quotes off of attribute values only if the value doesn’t contain spaces, otherwise the HTML processor can’t tell when an attribute ends. Even so, it’s not recommended; you should always quote HTML attributes.
should work. The call to
addslashesescapes quotes, which would otherwise cause another problem (ending the attribute or string argument ofshowUsertoo soon).