Jquery表单验证和提交 [英] Jquery form validation and submission

查看:119
本文介绍了Jquery表单验证和提交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用jquery和ajax提交表单。我一直在这里过去2天,但我不知道为什么这不工作。基本上,问题是:


  1. 获取发送请求,而不是发送

  2. 表单数据未验证

表示第一个问题,也试过使用$ .post(),但是也不工作。我试着使用dataType:'text',这也没有工作。另外,如@AnilPanwar指出,我使用#formdata而不是这,这不工作



我不知道为什么第二个问题存在。我已经改变了我的代码的结构,但是数据没有被验证。我已经单独测试了函数并且它们工作,但是当按下提交按钮时它们不工作,即if条件假定发送post数据返回false(转到else),即使在if条件分别是真的



第三个问题,我怀疑,可能是由于第一个。我不太确定。



脚本包括jquery.min.js 1.11.1,twitter bootstraps.min.js



请帮助我。

 <!DOCTYPE HTML& 
< html>
< head>
< title>实时信息a Sports类别Flat Bootstrap Responsive Website Template |首页:: w3layouts< / title>
< meta name =viewportcontent =width = device-width,initial-scale = 1>
< meta http-equiv =Content-Typecontent =text / html; charset = utf-8/>
< meta property =og:titlecontent =Vide/>
< meta name =keywordscontent =Live info Responsive web template,Bootstrap Web Templates,Flat Web Templates,Android Compatible web template,
Smartphone兼容的网页模板,免费网页设计为诺基亚, LG,SonyEricsson,Motorola web design/>

< / head>


<?php

session_start();
include'db.php';
if(isloggedin()== 0){
include'header.php';

?>

< br>< br>
< form id =formdata>
< div class =contact signup-body>
< div class =login-body>
< div class =login-heading>
< h3>注册< / h3>
< / div>
< div class =login-info>
< input type =textclass =userid =namename =nameplaceholder =Name>
< div id =namemstyle ='text-align:center; color:red;'>< / div>

< input type =textclass =userid =emailname =emailplaceholder =Email>
< div id =emailmstyle ='text-align:center; color:red;'>< / div>

< input type =textclass =userid =mobilename =mobileplaceholder =Phone>
< div id =mobilemstyle ='text-align:center; color:red;'>< / div>

< input type =passwordid =passwordname =passwordclass =lockplaceholder =Password>
< div id =passmstyle ='text-align:center; color:red;'>< / div>

< input type =passwordid =repasswordname =repasswordclass =lockplaceholder =Confirm Password>
< div id =repassmstyle ='text-align:center; color:red;'>< / div>

< input type =submitid =signinname =signinvalue =注册>
< div class =signup-text>
< a href =#data-toggle =modaldata-target =#myModal>已有帐户?在此登录。< / a>
< / div>
< / div>
< / div>

<! - Modal - >

<! - // Modal - >
< / div>
< / form>
<! - // contact - >
< / div>


< script src =js / jquery-1.11.1.min.js>< / script>
< script>
$(document).ready(function(){

$('#signin')。click(function(event){
event.prevetnDefault();
var name = $('#name')。val();
var email = $('#email')。val();
var mobile = $('#mobile') .val();
var password = $('#password')。val();
var repassword = $('#repassword')。val();
$ b b var email_filter = / ^([a-zA-Z0-9_\.\-])+ \ @(([a-zA-Z0-9 \-])+ \。)+ a-zA-Z0-9] {2,4})+ $ /;
var mob_fil = / ^ [0-9] {10} $ / i;
var string = / ^ [a -zA-Z] + $ /;
var pass = /^[a-zA-Z0-9_\]\-\@\!]*$/;


if(!(name ==''|| email ==''|| mobile ==''|| password ==''|| repassword =='')){

if(!email_filter.test(email)){$('#emailm')。html('Please provide a valid email address');}

if(!mob_fil.test移动)){$('#mobilem')。html('请输入一个10位数字');}

if(!string.test(name)){$('#namem' ).html('Please enter only alphabets');}

if(!pass.test(password)){$('#passm')。html('Only alphabets,digits and special characters允许在密码');}

if(password.length <3){$('#passm')。html('请输入更大的密码');}

if(password!= repassword){$('#repassm')。html('Password and Confirm password do not match');}
}

if((email_filter。 test(email)== true)&& (mob_fil.test(mobile)== true)&& (string.test(name)== true)&& pass.test(password)&&& (password.length> 3)&& (password = repassword))
{
var dataString = $('#formdata')。serializeArray();

$ .ajax({
type:POST,
url:register.php,
data:dataString,
dataType:文本,
contentType:'application / x-www-form-urlencoded',
cache:false,
success:function(result){
var data =
$(#message)。html('success');
$(#name)。val('');
$(#email)。val ('');
$(#mobile)。val('');
$(#password)。 ).val('');
},
error:function(error){console.log(error);}
}
}
else {$('#repassm')。html(您的表单无效);}

});

});
< / script>

<?php include'login_modal.php'; session_destroy();}
else {$ url ='index.php'; echo'< META HTTP-EQUIV = REFRESH CONTENT =0;'。$ url。'>';}?



<! - main content end - >
< / div>
< / div>
< / div>
<?php include'footer.php'?>
< / section>
< / body>
< / html>

同样,使用控制台没有显示任何js错误。在点击提交时,从网页发送GET请求,并在网址中包含字段值。



以下是我拍摄的表单



提交表单后控制台的快照:



请求的快照后控制台的快照:



正如@ADyson指出,不存储输入到表单中的数据。我移动了提交函数内的变量声明来解决。这解决问题编号3.但现在,我不能获取数据到我的脚本,当我再次按提交按钮。

解决方案

您的表单正在提交完全刷新)之前可以进行ajax调用。这就是为什么您看到一个GET请求。这是因为您的按钮 input [type =submit]



解决方案:

p>首先,将 event.preventDefault(); 移动到点击事件的第一行。这将阻止表单提交发生。目前,预防在过程中发生的太晚了(而且在表单无效时根本不会发生)。



其次,如注释中所述,替换 $(#this)。serializeArray(); 使用 $(#formdata)serializeArray(); 。在点击事件的上下文中, $(this)表示点击的按钮,而不是整个表单。



第三,移动

  var name = $('#name')。 
var email = $('#email')。val();
var mobile = $('#mobile')。val();
var password = $('#password')。val();
var repassword = $('#repassword')。val();

否则,验证可能会失败,因为目前这些变量是在页面加载时填充,而不是当用户提交时。如果您随后使用这些变量检查提交时数据的有效性,则不会考虑用户输入字段的方式。



最后,删除 event.unbind(); 完全。取消绑定适用于元素,而不适用于事件。我不认为这个命令实际上做任何不好的事,但最好是删除冗余/不正确的代码。有关如何使用此方法,请参见 http://api.jquery.com/unbind/ 。 p>

I am trying to submit a form using jquery and ajax. I have been at this for the past 2 DAYS but i do not know why this isn't working. Basically, the issues are:

  1. Get request sent instead of post
  2. Form data not being validated
  3. the form is reset after i press submit button.

for the 1st problem, I have tried using $.post() as well, but that doesn't work either. I tried using dataType:'text', which didn't work either. Also, as @AnilPanwar pointed out, i used #formdata instead of this , which didn't work either

I have no idea why the second problem exists. I have changed the structure of my code time and again, but data is not being validated. I have tested the functions separately and they work, however they do not work when the submit button is pressed, i.e the if condition that is supposed to send the post data returns false (goes to else), even when the tests inside the if condition are true individually

the 3rd problem, i suspect, is probably due to the first. I am not so sure though.

scripts pre included are jquery.min.js 1.11.1, twitter bootstraps.min.js

Please, please help me out.

<!DOCTYPE HTML>
<html>
<head>
<title>Live info a Sports Category Flat Bootstrap Responsive Website Template | Home :: w3layouts</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta property="og:title" content="Vide" />
<meta name="keywords" content="Live info Responsive web template, Bootstrap Web Templates, Flat Web Templates, Android Compatible web template, 
Smartphone Compatible web template, free webdesigns for Nokia, Samsung, LG, SonyEricsson, Motorola web design" />

</head> 


<?php 

    session_start();
    include 'db.php'; 
    if(isloggedin() == 0) {
        include 'header.php';

     ?>

            <br><br>
<form id="formdata">        
<div class="contact signup-body">
                <div class="login-body">
                    <div class="login-heading">
                        <h3>Sign up</h3>
                    </div>
                    <div class="login-info">
                            <input type="text" class="user" id="name" name="name" placeholder="Name" >
                        <div id="namem" style='text-align:center;color:red;'></div>

                            <input type="text" class="user" id="email" name="email" placeholder="Email">
                        <div id="emailm" style='text-align:center;color:red;'></div>

                            <input type="text" class="user" id="mobile" name="mobile" placeholder="Phone">
                        <div id="mobilem" style='text-align:center;color:red;'></div>

                            <input type="password" id="password" name="password" class="lock" placeholder="Password">
                        <div id ="passm" style='text-align:center;color:red;'></div>

                        <input type="password" id="repassword" name="repassword" class="lock" placeholder="Confirm Password"                            >
                            <div id = "repassm" style='text-align:center;color:red;'></div>

                            <input type="submit" id="signin" name="signin" value="Sign up">
                            <div class="signup-text">
                                <a href="#"  data-toggle="modal" data-target="#myModal">Already have an account? Login here.</a>
                            </div>
                    </div>
                </div>

                <!-- Modal -->

                <!-- // Modal -->
            </div>
</form>
            <!-- //contact -->
        </div>


 <script src="js/jquery-1.11.1.min.js"></script>
<script>
  $(document).ready(function(){ 

      $('#signin').click(function(event){
       event.prevetnDefault();
       var name = $('#name').val();
     var email = $('#email').val();
     var mobile = $('#mobile').val();
     var password = $('#password').val();
     var repassword = $('#repassword').val();

    var email_filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    var mob_fil = /^[0-9]{10}$/i;
    var string = /^[ a-zA-Z]+$/;
    var pass = /^[a-zA-Z0-9_\.\-\@\!]*$/;


          if (!(name == '' || email == '' || mobile== '' || password == '' || repassword == '')){

          if (!email_filter.test(email)) {$('#emailm').html('Please provide a valid email address');}

    if (!mob_fil.test(mobile)) {$('#mobilem').html('Please enter a 10 digit number');}

    if (!string.test(name))  {$('#namem').html('Please enter only alphabets');}

    if (!pass.test(password)) {$('#passm').html('Only alphabets,digits and special characters allowed in password');}

    if(password.length<3) {$('#passm').html('please enter a bigger password');}

    if (password!=repassword) {$('#repassm').html('Password and Confirm password do not match');}
           }

        if((email_filter.test(email)==true) && (mob_fil.test(mobile)==true) && (string.test(name)==true) && pass.test(password) && (password.length>3) && (password=repassword))
                            {
                    var dataString = $('#formdata').serializeArray();

                            $.ajax({
                                    type: "POST",
                                    url: "register.php",
                                    data: dataString,
                                    dataType:"text",
                                    contentType: 'application/x-www-form-urlencoded',
                                    cache: false,
                                    success: function(result){
                                    var data="";
                                    $("#message").html('success');
                                    $("#name").val('');
                                    $("#email").val('');
                                    $("#mobile").val('');
                                    $("#password").val('');
                                    $("#repassword").val('');
                                    },
                                    error: function(error){console.log(error);}
                            });   
                        }
          else {$('#repassm').html("your form is not valid");}

      });

  });
</script>

    <?php include 'login_modal.php';session_destroy();}
          else {  $url = 'index.php'; echo '<META HTTP-EQUIV=REFRESH CONTENT="0; '.$url.'">';} ?>



      <!-- main content end-->
</div>
</div>
</div>
<?php include 'footer.php' ?>
</section>
</body>
</html>

also, using console there are no js errors shown. A GET request is sent from the page when submit is clicked, with the field values in the URL.

Below are the links to snaps i took of the form

a snapshot of the console after submitting the form:

a snapshot of the requests after submitting the form:

As @ADyson pointed out, the data inputted into the form is not being stored. I moved the variable declarations inside the submit function to solve that. That does solve problem number 3. But now, i cannot get data into my script when i press the submit button for a second time. I have put the edited code into the question.

解决方案

Your form is submitting (in the conventional way with a full refresh) before the ajax call can be made. That's why you're seeing a GET request. This happens because your button is input[type="submit"]. The default behaviour of this type of button is to submit the form it is within when clicked.

The solution:

First, move event.preventDefault(); right to the first line of your click event. This will stop the form submission from happening. Currently the prevention is happening too late in the process (and not at all when the form is invalid).

Second, as mentioned in the comments, replace $("#this").serializeArray(); with $("#formdata").serializeArray();. In the context of the click event, $(this) means the button that was clicked, not the whole form.

Third, move

       var name = $('#name').val();
 var email = $('#email').val();
 var mobile = $('#mobile').val();
 var password = $('#password').val();
 var repassword = $('#repassword').val();

inside your click event. Otherwise the validation will probably fail, because currently these variables are being populated when the page loads, not when the user submits. If you then use these variables to check the validity of the data at submission, they don't take into account what the user has entered into the fields.

Lastly, remove event.unbind(); entirely. Unbind applies to elements, not to events. I don't think this command is actually doing anything bad necessarily, but it's better to remove redundant/incorrect code. See http://api.jquery.com/unbind/ for how to use this method.

这篇关于Jquery表单验证和提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆