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?
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.
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With