Can I write Javascript in PHP?

Asked

Viewed 31,971 times

9

I can write in the tag <script> and inside write the Javascript script </script> using echo?

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

This is my code but the 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>

");

I’ve decided to post my similar questions

I can make Javascript write PHP?

I can write ajax and javascript together?

  • 1

    Yeah, you’re making a mistake with that?

  • Javascript does not work I must have something wrong then

  • I don’t think this is a good idea. But you can do a nice little thing using ob_start

  • I ask you to consider my answer as an example to improve these practices. I believe @bigown’s response has already been enlightening to you.

4 answers

14


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 "linguing" text that will be sent to the HTTP server that it sends to the browser or whoever has requested it. It may be until it’s not an HTML page you’re making. Understand PHP code as a great word processor.

Of course it can do much more than that, but in the way it is usually used the end result will always be the text that can contain anything you want, can have HTML, JS, CSS, JSON, plain text, or any other format. Actually it doesn’t even have to be text, this is the type of data generated for the most common output. If the text has something wrong inside it, it’s not a PHP problem.

It may seem confusing because it is the code of a language within the code of another language. These codes have no relation to each other. They do not "talk", because the JS code is not executed by PHP, for it is just any text, only you know that is JS. When it is programmed think of PHP code independently of JS. The problem of one is not the problem of the other.

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 (it is possible to use it in other ways, but most programmers do not know how to do this and do not even know it is possible). Obviously where to put this echo in the code is important to achieve the expected result.

Have you ever tried to see in the browser the result of a page generated with PHP? Do experiments trying to send in different ways and whenever you have specific questions, post here giving as much detail 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 the PHP code itself and execute on it, then the answer is no, you cannot do this, they are separate languages. There may even be some way to call a mechanism that runs the JS externally, but it’s something no one does and it’s really weird. I see no reason to do this.

Specific problem

Note that the ideal is that you do not have JS code inserted within an HTML page. It would be better to have all JS code in a separate file, and preferably this file would be static, that is, it would be fixed and not generated on time.

Dynamically generating JS code via PHP usually makes little sense most of the time. Insert it into the JS is not usually necessary either, although it can be used smoothly.

After editing the question I see that the code is doing what you want, or not? Put it to run? It appeared in the browser? That’s it. Of course this code assumes that there are other HTML 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 configure it to manipulate the color by parameter and only the color to be inserted in the call of this code. You need to see a bigger context. But I reinforce what I said before, in general there is no reason to generate JS code by PHP.

If the JS is not generated ok and does not work, the problem is another one described in the question, then you should open another question with its specific problem. Post the rest of the code of the page in this new question. I believe it is not necessary anything PHP, even because this was not put effectively.

  • Thanks clarified my doubt I knew html could put inside php but I didn’t know I could still put javascript inside.

  • Note that at the bottom you are putting HTML that by chance inside it has JS. But could by pure JS also.

  • I’m still learning so I’m experiencing is the best way

3

You can yes.

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

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

ob_start function

The function ob_start allows you to capture the output buffer that PHP generates for memory. Thus, it is possible to capture this output (before going to the browser, roughly) and save 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 content of an HTML, rather than a PHP string) and save 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.

file_get_contents function

If you really need it, have you considered the possibility of 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 the Syntax Heredoc. But when using it you will not be worried if you have to use ' single quotes or " double quotes.

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

Completion

I have already written a code to debug PHP values through the browser console. For that I wrote a little code that way:

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

-2

Take the word var out of the function argument, and see if it works, as below:

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

");

-2

document.body.style.backgroundColor = red; 

swap the red for cor. There is no variable red.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.