I'm trying to call a javascript function with one argument being a variable gotten from a drop box. This script works fine if only passed the value from the current drop box using "this.value", however when trying to pass the variable the code doesn't work. The variable is properly being populated from the value in the drop box when I use echo statements. I think the problem is with actually passing the variable to the javascript function. The function showSection(q, r) is never being called as the write statement is never executing. Any help would be appreciated. Here is my php and javascript code

echo "<select name=\"course\" onchange=\"showSection($q, this.value)\">";
share|improve this question
a wall of code isn't that nice of a greeting. – Joseph the Dreamer Apr 21 '12 at 3:16
3  
This PHP code is just pleading to be MySQL injected. – Blender Apr 21 '12 at 3:17
This is the question. what is the syntax for passing the variable to the function, whichever way I try to pass the variable to the function it doesn't work. It only works when I pass one variable using this.value not a stored variable – nofx1129 Apr 21 '12 at 3:22
try to examine the resulting markup in the browser and see if it is correct. in addition, check the HTTP traffic and see if the server returns the correct response. – akonsu Apr 21 '12 at 3:40
The first two drop boxes are coming up, the function that calls the third file is never being called because of a problem with the passed parameters – nofx1129 Apr 21 '12 at 3:42
show 4 more comments

2 Answers

If the $q or this.value are string values, you have to pass it within quotes.

echo "<select name='course' onchange='showSection(\"$q\", \"this.value\")'>";
share|improve this answer

You need to make sure inserting the value of $q doesn't produce javascript syntax errors. The reasonable way to do that is to use json_encode on the value.

After that you need to make sure both single and double quotes are escaped in that value, to keep the html correct. htmlspecialchars is used for that. In my opinion, converting both single and double quotes always (ENT_QUOTES) is the best choice.

And the end result is (I'm using heredoc syntax here, because I find it more readable):

$escaped = htmlspecialchars(json_encode($q), ENT_QUOTES);
echo <<<HTML
<select name="course" onchange="showSection($escaped, this.value);">
HTML;
share|improve this answer

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.