dongyong3223 2014-05-06 14:18
浏览 73
已采纳

使用AJAX和JQuery使用PHP进行简单验证

I am new to AJAX, and I want to learn how to validate a form. Suppose, I have a form with two input fields. When I click in submit I want to check the page with a php script.
When the validation is succesfull I want to redirect to the action="submitForm.php". When one or more fields are not valid according to the validation.php I want to stay on the page and gives a error message next to the field.

What is the best way to do that?

<html>
    <head>
    </head>
    <body>
        <form action="submitForm.php" action="POST">
            <input type="text" name="username" />
            <input type="password" name="password" />
            <input type="submit" name="submit" />
        </form>
    </body>
</html>

submitForm.php:

<?php
    echo $_POST["username"];
    echo "<br />";
    echo $_POST["password"];
?>
  • 写回答

2条回答 默认 最新

  • doutang1873 2014-05-06 14:28
    关注

    In order to process the fields before actually submitting the form, you can catch its submit event:

    <form action="submitForm.php" action="post" onsubmit="return MyValidation()">
    

    Then, in your javascript:

    function MyValidation() {
        var valid = false;
    
        $.ajax({
            type: "POST",
            url: "validation.php",
            async: false,
            data: { name: $('#username').val(), password : $('#password').val() }
        })
        .done(function( data ) {
            if(data == 'true') {
                valid = true;
            }
        });         
    
        // not valid, return false and show some hidden message
        return valid;
    }
    

    (you need to add an ID to the <input> fields in order for the jquery selectors to work...)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)