javascriptonclick

I'm learning AJAX and I need to write a function to send to PHP script an argument from onclick JS event and first button click do nothing


HTML file:

<!DOCTYPE html>
    <html>
        <head>
            <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
            <script>
                
                var btn1Click = function(num){
                    $(document).ready(function(){
                        $("#btn1").click(function(){
                            $.post("index.php",
                                {
                                    num: num
                                },
                                function(data, status){
                                    alert(status);
                                    $("#test").html(data);
                                });
                        });
                    });
                };
    
            </script>
        </head>
        <body>
            <div id="test">
                <p>This is the first content!</p>
            </div>
            <button id="btn1" onclick="btn1Click(btn1.textContent)">Click to change</button>
            <button id="btn2">2 change</button>
        </body>
    </html>

PHP file:

    <?php
    echo "<p>{$_POST["num"]}</p>";
    echo "<input type=\"checkbox\" id=\"chk\">Wybierz";
?>

First click does nothing. Next click I see alert window 2 time, next 3 time, and every additional click make alert appears one more time.


Solution

  • Just change listener as a jquery listener, get textContent by jquery.text(); You don not need to create btn1Click function, as your code generate listener every time you run btn1Click() function

    <!DOCTYPE html>
    <html>
    <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    
    </head>
    <body>
    <div id="test">
    <p>This is the first content!</p>
    </div>
    <button id="btn1">Click to change</button>
    <button id="btn2">2 change</button>
    
    
    <script type="text/javascript">
    
    $(document).ready(function(){
     $("#btn1").click(function(e){
      e.preventDefault();
      let nums = $(this).text();
      $.post("index.php", {
       'num': nums
      },
      function(data, status){
       alert(status);
       $("#test").html(data);
      });
     });
    });
    
    </script>
    </body>
    </html>