frrlod
frrlod

Reputation: 6685

Calling a javascript function on a php variable

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.

Upvotes: 0

Views: 75

Answers (2)

gmmiso88
gmmiso88

Reputation: 17

echo "You have chosen a <script>document.write(capitalizeFL('".$race."'));</script>";

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

Upvotes: 1

Quentin
Quentin

Reputation: 943157

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>";

Upvotes: 6

Related Questions