首页 > 解决方案 > Stop link-forward when clicking on button with form-action

问题描述

I have created this code that allows to calculate som values. When clicking on the calculate-button it simply shows the result. By itself the code works perfectly fine.

To being able to log the data, it also sends an email of the inserted values by using a form and an action linked to a php-file. After adding this form to the code, it wrongfully redirects to the forms action-url. Ideally it it should show the result of the calculation on the webpage without reloading or redirecting when pressing the button.

I've tried to use "return false" without any luck. When changing/adding the button-type, it will either block the function of the calculation or redirect.

HTML-file:

<form action="/php/calcA.php" method="POST" role="form">
    <p>Value A</p>
    <input type="number" id="num1" style="text-align: center;" class="form-control" name="num1" required="required" data-error="Value is required.">
    <p>Value B</p>
    <input type="number" id="num2" style="text-align: center; class="form-control" name="num2" required="required" data-error="Value is required."></p>

    <button type="button" onClick="calculate()" class="btn btn-primary blueline" style="color: #FFF; font-weight: 700;">Calculate</button>
    <br>
    <h4 class="main" style="margin-left: 25px; margin-right: 25px; background: #1CBC55; color: #FFF; text-align: left; font-weight: bold" id="answer">Savings in total:</h4>     
<script>
    function calculate(){
        var field1=document.getElementById("num1").value;
        var field2=document.getElementById("num2").value;

        var result=parseFloat(field1)*parseFloat(field2)-(2000*parseFloat(field1));

     if(!isNaN(result)) {
        document.getElementById("answer").innerHTML="Savings in total: €"+result+".00 excl. VAT";
     }

        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
            }
        };
        xhttp.open("POST", "php/calcA.php", true);
        xhttp.send();
}
</script>
</form>

PHP-file:

    $num1 = $_POST['num1'];
    $num2 = $_POST['num2'];

    $email_from = 'Data from calcA';
    $email_subject = 'Data from CalcA';
    $email_body =
                "$num1\n".
                "$num2\n"

    $to = "data@youremail.com";
    $headers = "From: $email_from \r\n";
    $headers = "Reply-To: $email \r\n";

mail($to,$email_subject,$email_body,$headers);

标签: phphtmlinputhtml-email

解决方案


告诉 Javascript 阻止表单发布:

<form action="/php/calcA.php" method="POST" role="form" onsubmit="return handleForm();">
    <blah></blah>
<form>
<script type="text/javascript">
    function handleForm(e) {
        e.preventDefault(); // form will now not submit    
        // do your thing!
    }
</script> 

推荐阅读