Including Javascript in PHP and vice versa


#1

Hi there,

I have a PHP file which I am trying to insert some jQuery into and within the jQuery insert some PHP.

This is what I have, which is wrong, but I can't work out how to include each in one another:

<?php
<script>
	jQuery("section#title").append(<?php the_title( '<h1 class="product_title entry-title">', '</h1>' );?>);
</script>
?>

What would be the best way to do this?

Thank you.


#2

If you enabled the PHP excellent error reporting there would have been error messages and warnings displayed which could have been copied and pasted into your browser. No doubt there would be thousands of solutions available to immediately try to solve the problem.

The errors I should imagine would state that the script tag is not PHP script or something like that.

Try this:

<?php
// this is PHP script

?>
<!-- this is HTML script -->
<script>
	jQuery("section#title").append(<?php the_title( '<h1 class="product_title entry-title">', '</h1>' );?>);
</script>
<?php
// more PHP script
// not required to close PHP script if there is no more HTML script ?>

#3

Including Javascript in PHP and vice versa

You are aware that PHP and JavaScript run on different machines at different times?


#4

Thank you, the above code worked. Yes I'm aware of that they run differently.

Thanks again


#5

Did you activate error_reporting, etc and notice the errors?


#6

I want to offer some advice from personal experience. Although it is quite possible to write PHP code that puts together HTML - which may include JavaScript tags with variables that have been assigned values from PHP - in various ways such as echoing HTML, going in-and-out of PHP, includes, etc. the code can get very messy and very difficult to work with very fast.

Although it can be debated how to go about it and what is "best", I think it is a good idea to keep things separated enough so that they are less confusing and less prone to mistakes. It is only natural that after an approach is found that works in simple uses to scale that same approach for more complex code. But depending on how attentive one is to details and how much work they want to invest in working with the code, at some point what worked for the simple will break down when used for the more complex.

Anyway tl;dr, I think if you keep the mixing of PHP and HTML to a minimum you'll have a much better time of it.


#7

I agree unfortunately it is a necessary evil with data driven sites so I have adopted the following practice which I think is far easier to read and also to debug. This is where most of a programmer's time is spent :frowning:

http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

<?php
// this is PHP script

// BEWARE: NO SPACES OR TEXT AFTER OPENING  ____TMP
// and
// BEWARE ONLY LINEFEED ALLOWED AFTER CLOSING ____TMP;

// REQUIRES TESTING 
   $title =  'the_title( "<h1 class="product_title entry-title">',  '</h1>' );

$tmp = <<< ____TMP
<!-- this is HTML script -->
<script>
	jQuery("section#title").append( $title );
</script>
____TMP;
echo $tmp;

// more PHP script
// not required to close PHP script if there is no more HTML script ?>

#8

Why do you prefere heredoc over

?>
<html here>
<?php

Also, even better would be use a templating engine like Twig and don't mix HTML and PHP at all.
One step further is to only use <script src="..."></script> and stop using inline scripts altogether, which has the added advatage that you can omit unsafe-inline from your content security policy reducing the chances of an XSS attack by a lot.

So then you would have

php:

$twig = /* instantiate twig here, see twig docs */
$twig->render('hello.html.twig', ['title' => 'hello world!']);

hello.html.twig:

<html>
   <head>
     <title>{{ title }}</title>
     <script src="hello.js"></script>
  </head>
  <body>
     <h1>{{ title }}</h1>
  </body>
</head>

hello.js

document.querySelector('h1').innerHtml = document.querySelector('h1').innerHtml + '!';

just a (very) basic example


#9

I have used heredoc for a long time and for me it simplifies scripts when there are a lot of functions, variables, constants, etc to be rendered in HTML:

I have never used Twig and believe it is some sort of library which adds an unnecessary overheard and extra processing which PHP heredoc does a lot simpler.

<?php 
# PREPARE VARIABLES FOR HEREDOC
  $ci_version = '<span class="flr">Fuelled by: CodeIgniter - ver: <b>' .CI_VERSION .'</b>&nbsp;</span>'; 

  $md5 = md5(base_url() .$this->uri->uri_string());
  $sra = $_SERVER['REMOTE_ADDR'] ;      
  $elt = $this->benchmark->elapsed_time();
  $mua = $this->benchmark->memory_usage();
  $tim = date('H:i:s');
  $ses = http_response_code();
  $log = $_SERVER['DOCUMENT_ROOT'] .'/' .APPPATH .'log-' .date('Y-m-d'). '.php';
  $fse = file_exists($log) ? number_format(filesize($log)) : 'No Errors';

  # BEWARE - elapsed_time DOES NOT WORK IF COMPRESSED
    echo <<< ____DXD
      <div id="debug" class="fsx lh2 bd4" >
        $ci_version
        <i class="fll fsx" title="$md5"> 
          Debug: 
          $sra / 
          $mua /
          $tim /
          $ses /
          $fse 
          </i>
        </div>
      </div>
____DXD;
//

Output:

Debug: 184.22.233.242 / 810,368Mb / 10:26:05 / 200 / No Errors Fuelled by: CodeIgniter - ver: 3.1.8



Edit:
Your example using HEREDOC and without curly braces:

# PREPARE VARIABLES
  $title = 'hello world';
  $body  = 'Normally obtained from database table ';
  $foot  = 'Normally obtained from database table ';

echo $tmp = <<< ____TMP
<html>
   <head>
     <title> $title </title>
     <script src="hello.js"></script>
  </head>
  <body>
   <h1> $title </h1>

   <div class="content"> 
     $body
   </div>

  <div class="footer">
    $foot
  </div>

  </body>
</head>
____TMP;
//

#10

Where are your calls to html_entities? Twig does that for me to help prevent XSS (and it never forgets!), but your heredoc is wide open to XSS attacks.

Also there is some overhead using Twig, but not a lot since everything is parsed to plain php the first time a template is rendered, and then reused the next time you render it.

There is also some stuff in Twig, like blocks and embed for template inheritance that would be a lot harder in plain PHP.

Too each their own but I would suggest to at least have a look at the docs for Twig to see what it's all about. https://twig.symfony.com/doc/2.x/intro.html


#11

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.