Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easier way to dynamically create Javascript using PHP

I'm currently using PHP to dynamically create a javascript which will be echoed on the page.

Sample Code:

$JS .= '<script>';

if($condition == true) {
    $JS .= 'alert("Yo its true omg!");
}

$JS .= "</script>";

As you can see, this will eventually get messy with ll the ' quotes and escaping of single quotes within the double quotes...

Is there a better way to do this?

like image 305
Nyxynyxx Avatar asked Jul 05 '11 14:07

Nyxynyxx


People also ask

Can you generate JavaScript code from PHP?

JavaScript is used as client side to check and verify client details and PHP is server side used to interact with database. In PHP, HTML is used as a string in the code. In order to render it to the browser, we produce JavaScript code as a string in the PHP code.

Can PHP generate dynamic page content?

The Components of a PHP Application. In order to process and develop dynamic web pages, you'll need to use and understand several technologies. There are three main components of creating dynamic web pages: a web server, a server-side programming language, and a database.

Can PHP echo JavaScript?

PHP developers tend to look for an equivalent to the echo statement when they need to display an output to the screen using JavaScript. Although JavaScript doesn't have an echo statement, you can use the document.

Can you mix JavaScript and PHP?

Besides, PHP and JavaScript similarities, these two languages are a powerful combination when used together. Large numbers of websites combine PHP and JavaScript – JavaScript for front-end and PHP for back-end as they offer much community support, various libraries, as well as a vast codebase of frameworks.


1 Answers

You want the heredoc syntax!

if($condition)
    $statement = <<<JS
        alert("Wohoo!");
JS;
else $statement = "";

$javascript = <<<JS
    <script>
        $statement
    </script>
JS;

To handle conditional statements inside heredoc strings, simply do the condition logic beforehand and insert empty or filled strings inside the heredoc string. You can insert variables into heredoc strings the same way you do normal strings.

If you think heredoc strings are a hassle to define, I agree with you. Unfortunately, as far as I know, it's the only way to escape the even greater quote escaping hassle (No pun intended).

like image 126
Hubro Avatar answered Sep 24 '22 09:09

Hubro