Javascript:提交按钮w / validation&隐藏的字段值

时间:2012-09-12 21:05:52

标签: php javascript ajax javascript-events

我正在进行一项任务,我将创建一个抵押计算器,使用Javascript / Ajax获取“金额融资”和“利率”来计算每月付款。 “金额”& “兴趣”由用户填写,每月付款在PHP程序中计算并发送回“付款”字段。

我需要验证用户输入,并获取“付款”字段以显示计算的付款。

现在,当我按下提交时,我如何对其编码进行验证,但计算出的付款的价值显示在单独的页面上(除了打印行之外,php页面是空白的。)

以下是HTML页面的代码:

<link rel="stylesheet" type="text/css" href="css/king.css" />

    <script>
    var XMLHttpRequestObject = false;

        if (window.XMLHttpRequest) {
          XMLHttpRequestObject = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
          XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
        }

        function calculateRate()
        {

          if(XMLHttpRequestObject) {

            XMLHttpRequestObject.open("POST", "assignment_8_calculate.php");

            XMLHttpRequestObject.setRequestHeader('Content-Type',
              'application/x-www-form-urlencoded');

            XMLHttpRequestObject.onreadystatechange = function()
            {
              if (XMLHttpRequestObject.readyState == 4 &&
                XMLHttpRequestObject.status == 200) {

                  var returnedData = XMLHttpRequestObject.responseText;

                  var payment = document.getElementById('payment');
                  payment.value = returnedData;
              }
            }

            var amount = document.getElementById('amount').value;
            var interest = document.getElementById('interest').value;

            XMLHttpRequestObject.send(amount);
            XMLHttpRequestObject.send(interest);

          }

          return false;

        }


    function validateForm()
    {
        var errmsg = '';

        var amount = document.getElementById('amount').value;

        if (amount == null || amount == "")
        {
          errmsg += "<br />You must enter an 'Amount Financed'";
        } else {

            if (isNaN(amount))
            {
                errmsg += "<br />'Amount Financed' must be a number";
            }

        }

        var interest = document.getElementById('interest').value;

        if (interest == null || interest == "")
        {
          errmsg += "<br />You must enter an 'Interest Rate'";

        } else {

            if (isNaN(interest))
            {
                errmsg += "<br />'Interest Rate' must be a number";
            }

        }

        var messageDiv = document.getElementById('messagediv');

        messageDiv.innerHTML = errmsg;

        if (errmsg == '')
        {
            return true;
        } else {
            return false;
        }

    }

    </script>

</head>

<body>
<body>
<a href="assignment_8.php"><img src="images/KingLogo.jpg"></a><br>

<div id="mortgagecalculatorresults">
<h2>Mortgage Calculation</h2>

<div id="calculator">

    <form id="mortgage" method="post" action="assignment_8_calculate.php">

    <table>
    <tr>
    <td>Amount Financed:</td>
    <td><input type="text" name="amount" id="amount" ></td>
    </tr>

    <tr>
    <td>Interest Rate:</td>
    <td><input type="text" name="interest" id="interest" ></td>
    </tr>

    <tr>
    <td>Calculated Monthly Payment:</td>
    <td><input type="text" disabled="disabled" name="payment" id="payment" ></td>
    </tr>
    </table>

    <p><input type="submit" value="Calculate Payment" onclick="return validateForm()" onsubmit=" calculateRate();">

    <input type="reset" />
    </p>

    </form>

</div>

<div style="color: red;" id="messagediv">
</div>


</body>
</html>

我也尝试在一个发送中将值发送到PHP程序,如下所示:

var sendValues = amount + '|' + interest;
XMLHttpRequestObject.send(sendValues);

这是PHP页面的代码(请注意,在代码中注释了我尝试发送一个值并在我的php中爆炸时的示例):

<?php
//$sendValues = $_POST['sendValues'];
$amount = $_POST['amount'];
$interest = $_POST['interest'];

//list($amount, $interest) = explode('|', $sendValues);

$payment = ($amount * $interest) / 12;
//$payment = $sendValues / 12;
$payment = number_format ($payment, 2);

print $payment;

?>

如果我将按钮编码为一个按钮而不是一个提交,直接连接到claculateRate函数并跳过验证,无用值将返回到隐藏字段而不发送到单独的PHP页面,但发送的值将始终是0.00。

感谢!!!

更新的代码:不工作 - 获取错误:

“不允许的方法

URL /testfiles/Ungar_Bradley_1585_PHPwithMySQL/assignment_8_mortgage.html不允许使用请求的方法POST。“

如果我只是将“按钮”类型更改为“提交”,那么我会在“付款”字段中获得0.00值,其中值将返回。

<html>
<head>

    <link rel="stylesheet" type="text/css" href="css/king.css" />

        <script>
        var XMLHttpRequestObject = false;

            if (window.XMLHttpRequest) {
              XMLHttpRequestObject = new XMLHttpRequest();
            } else if (window.ActiveXObject) {
              XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
            }

            function calculateRate()
            {

              if(XMLHttpRequestObject) {

                XMLHttpRequestObject.open("POST", "assignment_8_calculate.php");

                XMLHttpRequestObject.setRequestHeader('Content-Type',
                  'application/x-www-form-urlencoded');

                XMLHttpRequestObject.onreadystatechange = function()
                {
                  if (XMLHttpRequestObject.readyState == 4 &&
                    XMLHttpRequestObject.status == 200) {

                      var returnedData = XMLHttpRequestObject.responseText;

                      var payment = document.getElementById('payment');
                      payment.value = returnedData;
                  }
                }

                var amount = document.getElementById('amount').value;
                var interest = document.getElementById('interest').value;

                XMLHttpRequestObject.send(amount);
                XMLHttpRequestObject.send(interest);

              }

              return false;

            }


        function validateForm()
        {
            var errmsg = '';

            var amount = document.getElementById('amount').value;

            if (amount == null || amount == "")
            {
              errmsg += "<br />You must enter an 'Amount Financed'";
            } else {

                if (isNaN(amount))
                {
                    errmsg += "<br />'Amount Financed' must be a number";
                }

            }

            var interest = document.getElementById('interest').value;

            if (interest == null || interest == "")
            {
              errmsg += "<br />You must enter an 'Interest Rate'";

            } else {

                if (isNaN(interest))
                {
                    errmsg += "<br />'Interest Rate' must be a number";
                }

            }

            var messageDiv = document.getElementById('messagediv');

            messageDiv.innerHTML = errmsg;

            if (errmsg == '')
            {
                calculateRate();
                return true;
            } else {
                return false;
            }

        }

        </script>

</head>

<body>
<body>
<a href="assignment_8.php"><img src="images/KingLogo.jpg"></a><br>

<div id="mortgagecalculatorresults">
<h2>Mortgage Calculation</h2>

<div id="calculator">

    <form id="mortgage" method="post">

    <table>
    <tr>
    <td>Amount Financed:</td>
    <td><input type="text" name="amount" id="amount" ></td>
    </tr>

    <tr>
    <td>Interest Rate:</td>
    <td><input type="text" name="interest" id="interest" ></td>
    </tr>

    <tr>
    <td>Calculated Monthly Payment:</td>
    <td><input type="text" disabled="disabled" name="payment" id="payment" ></td>
    </tr>
    </table>

    <p><input type="submit" value="Calculate Payment" onclick="return validateForm()" onsubmit="return false;">

    <input type="reset" />
    </p>

    </form>

</div>

<div style="color: red;" id="messagediv">
</div>


</body>
</html>

2 个答案:

答案 0 :(得分:1)

我会改变一些事情,但我想这取决于你的老师会允许什么

我会在整个项目中使用jquery。

http://docs.jquery.com/Plugins/Validation将能够处理您需要的任何验证

以下代码可以更好地从php脚本中收集信息

$.ajax({
    data: {'amount':amount,'interest':interest},
    type: "POST",
    url: "assignment_8_calculate.php",
    success: function (data) {
        if (data) {
            alert(data);
        } else {
            alert('data not found');
        }
    }
});

答案 1 :(得分:1)

从表单元素中删除action="assignment_8_calculate.php",从提交按钮中删除onsubmit=" calculateRate();",在表单元素中添加onsubmit="return false;",最后在validateForm()函数中添加if (errmsg == '') { calculateRate(); } return false; 如果没有错误,则返回true,将其更改为

{{1}}