简体   繁体   English

jQuery 验证 submitHandler 在 $.ajax 发布表单数据中不起作用

[英]jQuery validation submitHandler not working in $.ajax post form data

I am using the jquery validate plugin to send data from form to mysql database.我正在使用 jquery 验证插件将数据从表单发送到 mysql 数据库。 the validation works well but after the button is clicked, the data isnt submitted to the database.验证工作正常,但单击按钮后,数据未提交到数据库。 but no response or error is generated.但没有响应或错误生成。 i think the error is in ajax part.我认为错误出在ajax部分。

The below file is db_connect.php, it executes.both echo are working下面的文件是 db_connect.php,它执行。两个 echo 都在工作

<?php

echo "hello";
/* Database connection start */
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "upscfpyl_test";
$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    echo "hi";
    //exit();
}
else{
    echo "hi2";
}
?>       

index.html - some code given below the div error is displayed but the content in it is hi2. index.html - 显示了 div 错误下方给出的一些代码,但其中的内容是 hi2。 I dont know why it has the content hi2.我不知道为什么它的内容是 hi2。 I had used echo "hi2";我用过 echo "hi2"; in db_connect.php [code given at the end] but did not return it to ajax.在 db_connect.php [最后给出的代码] 但没有将其返回给 ajax。

<div id="error"></div>
<form id="signupForm" method="post" action="#">
<input type="submit" class="btn btn-primary" value="Sign Up" id="button1" name="btn-save">
</form>

Ajax part:阿贾克斯部分:

$.ajax({
    type: 'POST',
    dataType: 'text',
    url: 'js/php/register.php',
    data: {
        name1: name,
        email1: email,
        mobile1: mobile,
        gender1: gender,
        password1: passwords
    },
    beforeSend: function() {
        $("#error").fadeOut();
        document.getElementById("button1").disabled = true; // this works
    },
    success : function(response) {
        if(response==1)
        {
            $("#error").fadeIn(1000, function()
            {
                $("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span>   Sorry email already taken !</div>');
                document.getElementById("button1").disabled = false;
            });
        } 
        else if(response=="registered")
        {
            window.location = "dashboard.html";
        } 
        else {
            $("#error").fadeIn(1000, function()
            {
                $("#error").html('<div class="alert alert-danger"><span class="glyphicon glyphicon-info-sign"></span>   '+response+' !</div>');
                document.getElementById("button1").disabled = false;
            });
        }
    }
});

register.php - to submit to database register.php - 提交到数据库

<?php
include_once("db_connect.php");


function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}


if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $name=test_input($_POST['name1']); // Fetching Values from URL.
  $email=test_input($_POST['email1']);
  $gender=test_input($_POST['gender1']);
  $mobile=test_input($_POST['mobile1']);
  $password= test_input(sha1($_POST['password1'])); // Password Encryption, If you like you can also leave sha1.

echo "pranav";    // these dont work
echo $name+$email+$gender; // this also doesnt work


  // Check if e-mail address syntax is valid or not
  $email = filter_var($email, FILTER_SANITIZE_EMAIL); // Sanitizing email(Remove unexpected symbol like <,>,?,#,!, etc.)
  if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
    echo $email;
  } 
  else{
    $result = mysql_query("SELECT * FROM users WHERE email='$email'");
    $data = mysql_num_rows($result);
    if(($data)==0){
      $query = mysql_query("insert into users(name, email, password, gender, mobile) values ('$name', '$email', '$password', '$gender', '$mobile')"); // Insert query
      if($query){
        echo "registered";
      }
      else
      {
        echo "Error....!!";
      }
    }
    else
    {
      echo "1";
    }
  }
}
?>  

    

You can open your browser console for checking logs.您可以打开浏览器控制台来检查日志。

if the dataType is JSON, it means that your server is returning a json.如果 dataType 是 JSON,则意味着您的服务器正在返回一个 json。 But this is not the case see https://api.jquery.com/jQuery.ajax/但事实并非如此,请参阅https://api.jquery.com/jQuery.ajax/


Try this code for your data serialization:尝试使用此代码进行数据序列化:

$("#your_form_id").submit(function(e){ 
    e.preventDefault(); 
    var datas = $(this).serialize(); 
    $.ajax({

        data: datas,
        // Or this
        data: 'key1=' + value1 + '&key2=' + value2 + '&key3=' + value3,

        // to match your server response
        dataType: "text"

        // Error warning
        .fail(function() {
           alert( "error" );
        })

    });
});

With the validation code of the form, we could better help you有了表单的验证码,我们可以更好地帮助您

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

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