\n"; echo "alert('Congrats'...">

Best way to enable javascript in php?

I'm doing it now.

 <?php
//show footer
echo "<script type='text/javascript'>\n";
echo "alert('Congrats');\n";
echo "</script>";

?>

Is there a better way than just repeating it?

+3
source share
6 answers

of course

?>
alert('Congrats');
<?
+3
source

Just put your JavaScript code outside of PHP tags:

<?php
  // your PHP code goes here
?>
// your javascript function out of the PHP tag.
function f() {
   alert('congrats');
}
+8
source

js, PHP, , , , js, - , .

+2

PHP PHP- (HTML/CSS/javascript) .

, , backend 12 .

:

- my_project
   - lib
      - PHP files here
   - templates
      - HTML templates here
   - public <- this is your document root for web server
     - index.php <- just a dispatcher
     - js
     - images
     - css
+2

HEREDOCS PHP "html". Javascript , PHP, html- ( "? > " php). , HTML Javascript, . , , :

'pure php':

<?php
   echo '<script>';
   echo '  var x = [' . $somePHPvar . '];';
   echo '  alert(x);';
   echo '<script>';
?>

'heredoc':

<?php
echo <<<EOF
    <script>
       var x = [{$somePHPvar}];
       alert(x);
    </script>
EOF;
?>

'html mode':

<?php ?>
<script>
    var x = [<?php echo $somePHPVar ?>];
    alert(x);
</script>

/ :

  • pure php: PHP, echo + $vars PHP-, html/javascript, , ( : )
  • heredoc: PHP, (' ") , html . PHP vars heredoc , , javascript/html . , . heredoc var, . HEREDOC .
  • 'html mode': / html, javascript, AND php . open/close php , , . (htmlspecialchars(), urlecncode(), html_strip_tags() ..), var. , PHP html/javascript-.

, , .

+1

model-view-controller JavaScript.

"view", JS:

myJavascript.js.php:

alert('hello bob');
alert('hello <?php echo $name; ?>');
alert('whats up?');

Your controller, jsController.php:

$name = "Jane";
0
source

Source: https://habr.com/ru/post/1738539/


All Articles