0

I want to execute a javascript function from a php file

Like:

<?php

$type=0;
echo('<img onclick="alert('.$type.')" src="picture.jpg"/>');

?>

Result : ok everything is workin. Now i want to do it with a string:

<?php

$type='e';
echo('<img onclick="alert('.$type.')" src="picture.jpg"/>');

?>

Result : Uncaught ReferenceError: e is not definedonclick @ loadPlayer2.php:2

<?php

$type='e';
echo('<img onclick="alert("'.$type.'")" src="picture.jpg"/>');

?>

Result : Uncaught SyntaxError: Unexpected token }

    <?php

$type='e';
echo('<img onclick="alert(\"'.$type.'\")" src="picture.jpg"/>');

    ?>

Result : Uncaught SyntaxError: Unexpected token ILLEGAL

<?php

$type='\e';

echo('<img onclick="alert("$type")" src="picture.jpg"/>');



?>

Result : Uncaught SyntaxError: Unexpected token }

2 Answers 2

3

Different contexts require different escaping. You are mixing PHP strings with HTML attributes and JavaScript strings.

  1. String interpolation only works in double quotes:

              alternate single+dbl quotes
                         ↓
      echo "<img onclick='alert(\"$type\")' src='picture.jpg'>"
                                ↑
                         escaped quote
    
  2. The $type variable can be transformed from a PHP String to a JS string per json_encode:

      $type = json_encode($type);
      echo "<img onclick='alert($type)' src='picture.jpg'>"
                                  ↑
                adds "double" quotes automatically
    
  3. And it's best to apply htmlspecialchars for the whole attribute:

      $type = json_encode($type);
      $onclick = htmlspecialchars("alert($type)");
      echo "<img onclick='$onclick' src='picture.jpg'>"
                             ↑
                escapes `"` into `&quot;` 
    
  4. So the resulting output should look like:

       <img onclick='alert(&quot;\\e&quot;)' src='picture.jpg'>
                                                              ↑
                                                      pseudo-XHTML begone
    

    And at this point, one could even use " for the attribute values again.

Sign up to request clarification or add additional context in comments.

Comments

0

SOLVED:

<?php

$type="e";

echo('<img onclick="alert(\''.$type.'\')" src="picture.jpg"/>');


?>

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.