简体   繁体   English

表单验证并提交ajax

[英]Form validation and submit ajax

I want to validate my form using ajax, and after it is validated, insert it into the database using ajax. 我想使用ajax验证我的表单,并且在验证之后,使用ajax将其插入数据库。

With this code, it shows the validation messages but it still inserts. 使用此代码,它显示验证消息,但仍会插入。

The problem I found is something with the submit button, if I change it into button instead of submit it inserts the form without validation (not even messages) and when I change it back to submit, it also submits the form but it shows the validation messages. 我发现的问题与提交按钮有关,如果我将其更改为按钮而不是提交,则会插入未经验证的表单(甚至没有消息),并且当我将其更改回提交时,它也会提交表单,但会显示验证消息。

Any idea how to insert after validation? 知道验证后如何插入吗? And why it's not working for me? 为什么对我不起作用?

Thanks 谢谢

index.php
    <!doctype html>
    <html>
    <head>
    <link rel="stylesheet" type="text/css" href="css/style.css">

    <meta charset="utf-8">
    <title>Form</title>
    </head>
    <script type="text/javascript" src="js/validate.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>


    <body>
    <div id="wrap">
    <table>
    <td>
        <form name="form">
            <tr>
            <p class="names">Voornaam:</p> <p><input type="text" name="voornaam" id="voornaam"></p>
            </tr>
            <tr>
             <p class="names">Achternaam:</p> <p><input type="text" name="achternaam" id="achternaam"></p>
            </tr>
            <tr>
             <p class="names">Telefoonnummer:</p> <p><input type="text" name="telefoonnummer" id="telefoonnummer"></p>
            </tr>
            <tr>
             <p class="names">Emailadres:</p> <p><input type="text" name="email" id="email"></p>
            </tr>
            <tr>
              <input class="knop" type="submit" name="insert" value="Opsturen" id="insert">
            </tr>
        </form>
    </td>
    </table>
    <br>
    <div id="berichten">

    </div>

    <script>
    var is_valid = true;
    var validator = new FormValidator('form', [{
        name: 'voornaam',
        display: 'Voornaam',    
        rules: 'required'
    }, {
        name: 'achternaam',
        display: 'achternaam', 
        rules: 'required'
    },{
        name: 'telefoonnummer',
        display: 'telefoon', 
        rules: 'required|numeric'
    },{
        name: 'email',
        display: 'email', 
        rules: 'required|valid_email'
    }], function(errors, event) {
        var berichten = document.getElementById('berichten');

        berichten.innerHTML = '';

        if (errors.length > 0) {
            is_valid  = false;
            for (var i = 0, l = errors.length; i < l; i++) {
                berichten.innerHTML += errors[i].message + '<br>';
            }

        }

    });
    </script>
    <script type="text/javascript">
        $(function(){
            $('#insert').click(function(){
                if(is_valid){
                var voornaam = $('#voornaam').val();
                var achternaam = $('#achternaam').val();
                var telefoonnummer = $('#telefoonnummer').val();
                var email = $('#email').val();

                $.post('action.php',{action: "button", voornaam:voornaam, achternaam:achternaam, telefoonnummer:telefoonnummer, email:email},function(res){
                    $('#result').html(res);
                });
                document.getElementById('berichten').innerHTML = 'Verstuurd!';   
                }
            });

        });
    </script>

    </div>
    </body>

</html>

action.php action.php

<?php
    //connectie
include ('connection.php');

    //als de knop is ingedrukt insert dan
    if($_POST['action'] == 'button'){

        $voornaam  = mysql_real_escape_string($_POST['voornaam']);
        $achternaam = mysql_real_escape_string($_POST['achternaam']);
        $email  = mysql_real_escape_string($_POST['email']);
        $telefoonnummer = mysql_real_escape_string($_POST['telefoonnummer']);

        $sql = "insert into 
           `form` (`id`,`voornaam`, `achternaam`, `email`, `telefoonnummer`) 
            values ('','".$voornaam."', '".$achternaam."', '".$email."', '".$telefoonnummer."')";
        $query = mysql_query($sql);
        if($query){
            echo "Toegevoegd!";
        }else {
            echo "Er is iets fout gegaan.";
        }
    }
?>

End your click handler function with: 使用以下命令结束click处理程序功能:

return false;

to prevent the default action of the submit button. 防止提交按钮的默认操作。

With submit button, when for is not valid you need to prevent dfault action by return false 使用提交按钮,当for无效时,您需要通过return false来防止dfault动作

 <script type="text/javascript">
        $(function(){
            $('#insert').click(function(){
                if(is_valid){
                var voornaam = $('#voornaam').val();
                var achternaam = $('#achternaam').val();
                var telefoonnummer = $('#telefoonnummer').val();
                var email = $('#email').val();

                $.post('action.php',{action: "button", voornaam:voornaam, achternaam:achternaam, telefoonnummer:telefoonnummer, email:email},function(res){
                    $('#result').html(res);
                });
                document.getElementById('berichten').innerHTML = 'Verstuurd!';   
                } return false;
            });

        });
    </script>

And by the way for security reason, and for the case when someone have js disabled you should validate data in php also. 顺便说一句,出于安全原因,并且在有人禁用js的情况下,您还应该在php中验证数据。

You can also try this : call this function on click like : 您也可以尝试:点击以下按钮调用此函数:

<button type="button"  class="btn btn-inverse"   name="submit" onClick="ajaxFormSubmit();">Test</button>

 function ajaxFormSubmit(){
    var voornaam = $('#voornaam').val();
        var achternaam = $('#achternaam').val();
        var telefoonnummer = $('#telefoonnummer').val();
        var email = $('#email').val();
        var atpos=email .indexOf("@");
    var dotpos=email .lastIndexOf(".");

    if(voornaam =="" || achternaam =="" || telefoonnummer =="" ||email ==""){
                  alert("message");       
          return false;
    }
    else if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length)
    {
     alert("msg");
      return false;
    }

    jQuery.post("your data",function(r){
        if(r=="success"){

        }
    });

There may be a JQuery conflict in your page, just add one jquery link in your page....Try just like this, 您的页面中可能存在JQuery冲突,只需在页面中添加一个jquery链接即可。...尝试像这样,

Jquery path: jQuery路径:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

Form 形成

<form name="myform">
<input type"text" name="name">
<input type="submit" name="submit" id="submitbtn" value="Submit" />
</form>

JS script under body tag 正文标签下的JS脚本

<script>
$('#submitbtn').click(function(){
    //ajax code here
    return false;
})
</script>

The above code is just a sample...workout your code like this... 上面的代码只是一个示例...像这样计算您的代码...

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

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