0

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.

3
  • 2
    capitalizeFL(my string) needs to be capitalizeFL('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 be O'Neil Commented May 9, 2013 at 9:28
  • Why not just use a PHP function to do this. Take a look at the following functions: - string strtoupper(string $string) Except ofcourse there's a specific reason why you are using a javascript function there. Commented May 9, 2013 at 9:35
  • @Bernard as I've mentioned in my question I could find other ways of doing it, just wanted to understand for the sake of learning. Commented May 9, 2013 at 13:36

2 Answers 2

6

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>";
Sign up to request clarification or add additional context in comments.

5 Comments

ie. document.write(capitalizeFL('".$race."'));
@Jace — That will break if the string contains ' characters.
@Waygood — Yes, but Jace's code doesn't do that (and your comment doesn't provide any code to do the escaping). Mine does (although it uses " instead of ').
I don't understand one thing. $race IS a string. Say it contains "human". Then wouldn't value_of_race be "human", already with quotes, rather than just human?
No. Quote marks delimit the start and end of a string literal (in both PHP and JavaScript). They aren't part of the string, they just contain it. If they were, then you would have " characters showing up every time you tried to print anything in PHP, which would be awful.
1
echo "You have chosen a <script>document.write(capitalizeFL('".$race."'));</script>";

You can try above code. Javascript string must be wrapped by ''.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.