Mou某
Mou某

Reputation: 596

javascript inside php - failing

Here's my code in side of my php file:

        echo '<script type="text/javascript">';
        echo '<audio id="player" src="../cdh/ba1.mp3"></audio>';
        echo '<a onclick="document.getElementById('player').play()"><i class='fa fa-lg fa-volume-up'>';
        echo '</script>';

I was basing this off of Ionuț G. Stan's answer on How to output JavaScript with PHP and Sykox's answer on Single icon sound player in html using font awesome. I just took out the divs changed the src & i class.

The line giving me issues has got to be:

echo '<a onclick="document.getElementById('player').play()"><i class='fa fa-lg fa-volume-up'>';

which gives the error:

Parse error: parse error, expecting ','' or';''

What am I doing wrong?!

Upvotes: 1

Views: 57

Answers (1)

Abhishek
Abhishek

Reputation: 1068

You have to escape single quotes inside.

echo '<a onclick="document.getElementById(\'player\').play()"><i class=\'fa fa-lg fa-volume-up\'></i></a>';

Or you can even use double quotes.

echo '<a onclick="document.getElementById("player").play()"><i class="fa fa-lg fa-volume-up"></i></a>';

PS: You have to close <a> tag as well.

Change your code to

echo '<a onclick="playAudio();"><i class=\'fa fa-lg fa-volume-up\'></i></a>'; 
echo '<script type="text/javascript">'; 
echo 'function playAudio(){var audio = new Audio("../cdh/ba1.mp3");'; 
echo 'audio.play();}'; 
echo '</script>';

The icon is not printing because it is under script tags.

Upvotes: 1

Related Questions