tags:

views:

172

answers:

3

hello, 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!

+7  A: 

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.

<a href="showUser('<?php echo addslashes($username) ?>')">user</a>

should work. The call to addslashes escapes quotes, which would otherwise cause another problem (ending the attribute or string argument of showUser too soon).

outis
Thank you a million! i can't believe how much time i spent trying to fix that error... very good lesson learned. Thank you :)
Rees
+2  A: 

Yes you can you are missing " in you xml attribute field: Each attribute must have a starting and an ending "

myField="blabla ..."

onClick="showUser(escape('<?php echo $deptname; ?>'))"
Patrick
What you're saying is *technically* incorrect, even though it's relevant to the problem here, since quotation marks aren't required for HTML attributes, only XHTML and XML attributes. Without the quotes any value without a space in it would parse correctly.
Andy E
You re right but i think it will be better to start with good habits and quote each attribute :)
Patrick
A: 

Try the Unicode escape sequence for a space character, '\u0020'.

ewg