Can I write in JavaScript within PHP?

8

Can I write the HTML tag <script> in PHP and write the script </script> using echo here?

If I do for example echo("<script> var a = 'texto';</script>");

This is my code but JS does not work:

$color = "red";
echo("
 <script>
  function change_background(var cor)
  {
     if(cor == 'red')
     {
      document.body.style.backgroundColor = red;
     }
  }
 </script>
 <button onclick='change_background('".$color."')'>$color</button>

");

Well I decided to post my similar questions

Can I make JavaScript write PHP?

Can I write ajax and javascript together?

    
asked by anonymous 30.09.2015 / 13:27

2 answers

13

JavaScript as text

If your question is whether you can create a text that contains a JS code that will be inserted along with the HTML text you are generating with PHP. Yes, you can.

What PHP does is just this, generate a "language" text that will be sent to the HTTP server it will send to the browser or who has requested it. It may be that it is not an HTML page you are doing. Understand PHP code as a great word processor.

Of course it can do much more than this, but in the way it is used the final result will always be text that can contain anything you want, it can have HTML, JS, CSS, JSON, plain text without formatting, or other format. Actually it does not even need to be text, this is the kind of data generated for most common output. If the text has something wrong inside it, it is not PHP problem.

It may seem confusing because it is the code of a language within the code of another language. These codes are unrelated. They do not "talk", even because the JS code is not executed by PHP. For him, this is just some text. Only you know that's JS. When programmed, think of PHP code independently of JS. The problem of one is not another's problem.

The echo is just for this. Everything you "print" in PHP will be sent to the HTTP server. At least this is the most common way to use PHP (you can use it in other ways, but most programmers do not know how to do this and do not even know it's possible). Of course, where to put this echo in the code is important to achieve the expected result.

Have you tried to see in the browser the result of a page generated with PHP? Make experiments trying to send in different ways and whenever you have specific questions, post here giving as much details as possible of what you are doing and what the problem is.

JavaScript running

If you want to know if you can insert this JS code into your own PHP code and run it yourself, then the answer is no, you can not do this. They are distinct languages. There may even be some way to call a mechanism that executes the JS externally, but it's something that nobody does and it's really weird. I see no reason to do this.

Specific problem

Note that ideally you do not have JS code inserted inside an HTML page. It would be better to have all JS code in a separate file, and preferably this file would be static, ie fixed and not generated on the fly.

Generating JS code dynamically via PHP usually makes little sense most of the time. Inserting it into JS also is not usually necessary, although it can be used without any problems.

After editing the question I see that the code is doing what you want, or not? Did he put it to perform? Did he appear in the browser? This is it. Of course this code assumes that other HTML parts or even JS parts on the same page or additional file.

But I have my doubts if you need to generate all this JS code in PHP. I think you can leave the JS separate and set it to handle the color per parameter and only the color to be inserted into the call of this code. You need to see a larger context. But reinforcing what I said before, usually does not have to generate JS code by PHP.

If JS is not generated ok and does not work, the problem is another one described in the question, so you should open another question with your specific problem. Post the rest of the page code in this new question. I do not think PHP is necessary, not even because it was actually placed.

    
30.09.2015 / 13:33
2

You can, yes.

The problem is that this makes it difficult to read your code (in javascript), since it is a PHP string, and it is hardly possible for your text editor to signal that the syntax is correct or not.

I do not know what the purpose of this is, but there are other things that PHP can do that you can take into account when using a javascript together.

ob_start function

The ob_start function allows you to capture the output buffer that PHP generates into memory. That way, you can capture this output (before going to the browser, roughly) and saving it in a string.

Example

<?php if ($alguma_coisa): ?>
<?php ob_start() ?>
<script>
alert('vou parar dentro do php');
</script>
<?php 
   $buffer_js = ob_get_clean();
    var_dump($buffer_js);
?>
<?php endif ?>

This can be useful if you want to write your javascript code normally (like the contents of an HTML, rather than a PHP string) and store it in memory. When we call the function ob_get_clean() we are capturing what was stored in the buffer and ending the capture of it - that is, only the javascript snippet will be caught.

function file_get_contents

If you really need it, have you thought about opening a javascript file by PHP and printing it as a string?

<script>
<?php echo file_get_contents('meu_arquivo.js') ?>
</script>

HEREDOC

Another good idea is to use Syntax Heredoc . But when using it you will not be concerned if you have to use ' single quotes or% with double quotation marks.

$script = <<<EOT
<script type="text/javascript">
   alert('teste'); alert("teste");
</script>
EOT;

Conclusion

I have in particular already written a code to be able to debug PHP values through the browser console. For this I wrote a small code like this:

function js_console_log($mixed) {
  printf('<script>console.log(%s);</script>', json_encode($mixed));
}
    
01.10.2015 / 18:35