Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put php inside JavaScript?

Tags:

javascript

php

I've tried (but its not working):

<?php     $htmlString= 'testing'; ?> <html>   <body>     <script type="text/javascript">         var htmlString=<?php echo $htmlString; ?>;       alert(htmlString);     </script>   </body> </html> 

Here is the tutorial that I've used for that purpose:

like image 570
Ben Avatar asked Jul 27 '10 15:07

Ben


People also ask

Can I add PHP inside JavaScript?

Yes, you can, provided your JavaScript code is embedded into a PHP file.

Can I run PHP code in JavaScript?

You can't. PHP is executed server side, and the finished content is sent to the browser. Javascript just sees the end result. All you can do is make an AJAX call and get the results from that.

Can we write PHP code in script tag?

Just write your php code in the javascript function or I'm the parameters. You can use PHP inside script tag too not a problem.


1 Answers

Try this:

<?php $htmlString= 'testing'; ?> <html>   <body>     <script type="text/javascript">         // notice the quotes around the ?php tag                var htmlString="<?php echo $htmlString; ?>";       alert(htmlString);     </script>   </body> </html> 

When you run into problems like this one, a good idea is to check your browser for JavaScript errors. Different browsers have different ways of showing this, but look for a javascript console or something like that. Also, check the source of your page as viewed by the browser.

Sometimes beginners are confused about the quotes in the string: In the PHP part, you assigned 'testing' to $htmlString. This puts a string value inside that variable, but the value does not have the quotes in it: They are just for the interpreter, so he knows: oh, now comes a string literal.

like image 148
Daren Thomas Avatar answered Sep 30 '22 07:09

Daren Thomas