Javascript:
function capitalizeFL(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
PHP:
echo "You have chosen a <script>document.write(capitalizeFL(".$race."));</script>";
$race contains a string. What I would like is simply to capitalize the first letter of the php variable $race, using the Javascript function above, and print it on the page.
I could find another way of doing this, but this JS-PHP mixing thing is confusing to me and I'd very much like to figure out WHY this doesn't work.
2 Answers 2
Look at the generated JavaScript.
document.write(capitalizeFL(value_of_race));
That's an identifier, not a string literal. You need to include quote marks in your generated JS.
Given a string, the json_encode function will output the equivalent JS literal (even if it isn't valid JSON). Use that to convert your PHP variables into JS literals.
$js_race = json_encode($race);
echo "You have chosen a <script>document.write(capitalizeFL($js_race));</script>";
5 Comments
' characters." instead of ')." characters showing up every time you tried to print anything in PHP, which would be awful.echo "You have chosen a <script>document.write(capitalizeFL('".$race."'));</script>";
You can try above code. Javascript string must be wrapped by ''.
capitalizeFL(my string)needs to becapitalizeFL('my string')so you need to delimit $race with'to identify it as a string and escape any'within the text too. e.g. your string could beO'Neil