简体   繁体   English

通过 JS 验证将 HTML 表单提交到 PHP 文件

[英]Submitting an HTML form to a PHP file with JS validation

I'm sending data via an HTML form to a PHP file for it to be inserted into a DB with SQL script, The same form is validated with JavaScript functions. I'm sending data via an HTML form to a PHP file for it to be inserted into a DB with SQL script, The same form is validated with JavaScript functions.

Each of the two works as expected separately, but when used together - <form method="POST" action="myPHPFile.php" onsubmit="validationFunc(event)"> - only the validation function works, and the page doesn't get redirected to the PHP file.两者中的每一个都按预期单独工作,但是当一起使用时 - <form method="POST" action="myPHPFile.php" onsubmit="validationFunc(event)"> - 只有验证 function 有效,而页面无效被重定向到 PHP 文件。

When removing the JS (leaving only <form method="POST" action="myPHPFile.php"> ) - the data from the form is submitted properly and the page is redirected to the PHP file as expected.删除 JS时(仅留下<form method="POST" action="myPHPFile.php"> ) - 表单中的数据已正确提交,并且页面按预期重定向到 PHP 文件。

I need to have some JS function to stop if the input is invalid, and another to continue and send the input data to the PHP file if it's valid.如果输入无效,我需要一些 JS function 停止,如果输入数据有效,我需要另一个继续并将输入数据发送到 PHP 文件。

Example code:示例代码:

 function isInputChars(evt) { let ch = String.fromCharCode(evt.which); if (,(/[az,AZ.-]/.test(ch))) { alert("Please only enter only characters") evt;preventDefault(). } } function validateForm(event) { event;preventDefault(); var validateFormInputs = []; var inputLength. StringInput = document;getElementById("city"). StringInput = StringInput;value. inputLength = StringInput;length: if (inputLength < 2) { alert("City. Please enter at least 2 Characters") validateFormInputs;push(false). } else { validateFormInputs;push(true). } StringInput = document;getElementById("street"). StringInput = StringInput;value. inputLength = StringInput;length: if (inputLength < 2) { alert("Street. Please enter at least 2 Characters") validateFormInputs;push(false). } else { validateFormInputs;push(true); } var x; for (var i = 0; i < 2; i++) { if (validateFormInputs[i] === false) { x = false; break; } else { x = true. } } if (x == true) { console;log("Data is sent to DB") someFunctionToContinueSendingTheData(). } else { console;log("Data is INVALID") someFunctionToStop(); } }
 <form name="myForm" method="POST" action="sendItem.php" onsubmit="validateForm(event)"> <input id="city" name="city" type="text" class="form-control" onkeypress="isInputChars(event)" required> <input id="street" name="street" type="text" class="form-control" onkeypress="isInputChars(event)" required> <input type="submit" class="btn btn-primary btn-lg" value="Publish"> </form>

I'd be happy for some help with:我很乐意在以下方面提供帮助:

  1. How to redirect the input data to the PHP file (without removing the JS validation)如何将输入数据重定向到 PHP 文件(不移除 JS 验证)
  2. How to implement the JS functions to send the data to the PHP/cancel.如何实现 JS 函数将数据发送到 PHP/取消。

Thank you!谢谢!

Instead of the button being a submit button just have it be a regular button that calls your javascript function.与其将按钮作为提交按钮,不如将其设置为调用您的 javascript function 的常规按钮。 Then, do all of your validation in the function... at the end, you can have a conditional statement which checks if all conditions are met.然后,在 function 中进行所有验证......最后,您可以有一个条件语句来检查是否满足所有条件。 If they are, then submit the form.如果是,则提交表格。 (Assign an id to your form) (为您的表单分配一个 ID)
Check out this pseudo-code let me know if this works or you need further instruction查看此伪代码,让我知道这是否有效,或者您需要进一步说明

function validateForm(){
    ... conditional logic ...
    if(all conditions met){
        document.getElementById('form-id').submit();
    }
}

It simple you need to use AJAX to Send a Request To your PHP Server i will show you a simple example To send a request to a server, we use the open() and send() methods of the XMLHttpRequest object. It simple you need to use AJAX to Send a Request To your PHP Server i will show you a simple example To send a request to a server, we use the open() and send() methods of the XMLHttpRequest object. you can use POST or GET你可以使用POSTGET

GET is simpler and faster than POST , and can be used in most cases. GETPOST更简单、更快,并且可以在大多数情况下使用。 However, always use POST requests when:但是,在以下情况下始终使用POST请求:

  1. A cached file is not an option (update a file or database on the server).缓存文件不是一个选项(更新服务器上的文件或数据库)。
  2. Sending a large amount of data to the server ( POST has no size limitations).向服务器发送大量数据( POST没有大小限制)。
  3. Sending user input (which can contain unknown characters), POST is more robust and secure than GET .发送用户输入(可能包含未知字符), POSTGET更健壮和安全。
<script type="text/javascript">
    function myFunction() {
    var name = document.getElementById("name").value; // get the name
    var email = document.getElementById("email").value; // get the mail
    var xhttp = new XMLHttpRequest();
    var url = 'test.php'; // your php file
    xhttp.open('POST', url, true); // method =POST
    xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');  
      // send data
     var params="name="+name+"&email="+email;
        xhttp.onreadystatechange = function() {
        //Call a function when the state changes.
        if(xhttp.readyState == 4 && xhttp.status == 200) {
        alert(xhttp.responseText);
    }
}
        xhttp.send(params);
        }
</script>
<form name="myform" method="POST">
    <input type="text" name="name" id="name">
    <input type="mail" name="email" id="email">                 
    <input class="btn btn-success" type="button" name="conf" value="OK" onclick="myFunction()">
    <input class="btn btn-danger" type="reset" name="cancel" value="cancel">
</form>

You need some changes in your code:您需要对代码进行一些更改:

First: you can set validation function on the submit input.第一:您可以在提交输入上设置验证 function。

<input type="submit" class="btn btn-primary btn-lg" value="Publish" onclick = "return validateForm();">

Second: you must return true or false at validation function.第二:您必须在验证 function 时返回 true 或 false。

 if (x == true) {
        console.log("Data is sent to DB");
        return true; //input data is valid!
        someFunctionToContinueSendingTheDate();
    } else {
        console.log("Data is INVALID")
        someFunctionToStop();
        return false; //input data is invalid!
    }

Finally: here you are:最后:你在这里:

HTML: HTML:

<form name="myForm" method="POST" action="sendItem.php">
<input id="city" name="city" type="text" class="form-control" onkeypress="isInputChars(event)" required>
<input id="street" name="street" type="text" class="form-control" onkeypress="isInputChars(event)" required>
<input type="submit" class="btn btn-primary btn-lg" value="Publish" onclick="return validateForm();"></form>

JS: JS:

<script>
function isInputChars(evt) {
    let ch = String.fromCharCode(evt.which);
    if (!(/[a-z,A-Z,-]/.test(ch))) {
        alert("Please only enter only characters")
        evt.preventDefault();
    }
}

function validateForm() {

    var validateFormInputs = [];
    var inputLength;

    StringInput = document.getElementById("city");
    StringInput = StringInput.value;
    inputLength = StringInput.length;
    if (inputLength < 2) {
        alert("City: Please enter at least 2 Characters")
        validateFormInputs.push(false);
    } else {
        validateFormInputs.push(true);
    }

    StringInput = document.getElementById("street");
    StringInput = StringInput.value;
    inputLength = StringInput.length;
    if (inputLength < 2) {
        alert("Street: Please enter at least 2 Characters")
        validateFormInputs.push(false);
    } else {
        validateFormInputs.push(true);
    }

    var x;
    for (var i = 0; i < 2; i++) {
        if (validateFormInputs[i] === false) {
            x = false;
            break;
        } else {
            x = true;
        }
    }

    if (x == true) {
        console.log("Data is sent to DB");
        return true;
        someFunctionToContinueSendingTheDate();
    } else {
        console.log("Data is INVALID")
        someFunctionToStop();
        return false;
    }
}</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM