how to write javascript code inside php

前端 未结 4 1545
轻奢々
轻奢々 2020-11-28 08:23

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
相关标签:
4条回答
  • 2020-11-28 08:24

    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).

    0 讨论(0)
  • 2020-11-28 08:35

    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

    0 讨论(0)
  • 2020-11-28 08:42

    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.

    0 讨论(0)
  • 2020-11-28 08:48

    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>
            ";
         }
      ?>
    
    0 讨论(0)
提交回复
热议问题