Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to write javascript code inside php

i have a got a form, on clicking the submit button:

  1. I want to do some task in the same file (db task) AND
  2. I want the form data to be sent to test.php with the redirection

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

like image 767
n92 Avatar asked May 15 '12 07:05

n92


People also ask

Can we write JavaScript code in 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.

How can you insert JavaScript in PHP code?

Java script can be inserted by embedding <script> tag in a php script as follows: 1) <? </script>"; ?>

Can you mix JavaScript and PHP?

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.


2 Answers

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>         ";      }   ?> 
like image 53
keto23 Avatar answered Sep 22 '22 23:09

keto23


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.

like image 26
Peter Dvukhrechensky Avatar answered Sep 21 '22 23:09

Peter Dvukhrechensky