简体   繁体   中英

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. 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.

The below file is db_connect.php, it executes.both echo are working

<?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. I dont know why it has the content hi2. I had used echo "hi2"; in db_connect.php [code given at the end] but did not return it to 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

<?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. But this is not the case see 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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