php - 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);
解决方案
告诉 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>
推荐阅读
- keras - 具有共享参数的并行 LSTM 模型
- android - 如何将图像设置为圆形?
- amazon-web-services - AWS lambda 执行超出超时限制
- multithreading - 用于多线程的 Scala 迭代器
- node.js - 在 Node.js 中为群聊应用程序实现端到端加密的好方法?
- swift - iOS:关闭应用程序时如何在后台运行代码?
- python - 在捕获输入错误后在第二次迭代中出现问题
- ios - 如何将表格视图单元格从一个表格视图移动到一个新的表格视图
- symfony - 使用 Symfony 5 信任 Heroku 路由器
- mysql - 我如何将此 mysql 语句转换为 hql