i have a got a form, on clicking the submit button:
here is my code
<?php if(isset($_POST['btn'])){ //do some task ?> <script type="text/javascript"> var e = document.getElementById('testForm'); e.action='test.php'; e.submit();</script> <?php } ?> <form name="testForm" id="testForm" method="POST" > <input type="submit" name="btn" value="submit" autofocus onclick="return true;"/> </form>
but not able to submit the form, if i call the javascript code on onClick, it works.what is the problem in this code, Is there any work around for 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.
Java script can be inserted by embedding <script> tag in a php script as follows: 1) <? </script>"; ?>
PHP is executed on the server, javascript on the client. You can't 'mix' them. When you call a PHP page the server parses the entire thing and executes anything inside PHP tags. The resulting text is then passed to the user's browser where any client side code is executed.
Just echo the javascript out inside the if function
<form name="testForm" id="testForm" method="POST" > <input type="submit" name="btn" value="submit" autofocus onclick="return true;"/> </form> <?php if(isset($_POST['btn'])){ echo " <script type=\"text/javascript\"> var e = document.getElementById('testForm'); e.action='test.php'; e.submit(); </script> "; } ?>
Lately I've come across yet another way of putting JS code inside PHP code. It involves Heredoc PHP syntax. I hope it'll be helpful for someone.
<?php $script = <<< JS $(function() { // js code goes here }); JS; ?>
After closing the heredoc construction the $script variable contains your JS code that can be used like this:
<script><?= $script ?></script>
The profit of using this way is that modern IDEs recognize JS code inside Heredoc and highlight it correctly unlike using strings. And you're still able to use PHP variables inside of JS code.
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