简体   繁体   中英

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

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.

You can put up all your JS like this, so it doesn't execute before your HTML is ready

$(document).ready(function() {
   // some code here
 });

Remember this is jQuery so include it in the head section. Also see Why you should use jQuery and not onload

At the time the script is executed, the button does not exist because the DOM is not fully loaded. The easiest solution would be to put the script block after the form.

Another solution would be to capture the window.onload event or use the jQuery library (overkill if you only have this one JavaScript).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM