在PHP中创建模态警报而不是页面重定向验证

时间:2015-03-11 01:51:04

标签: javascript php jquery mysql ajax

我想要进行服务器端验证。有没有办法如何在用户输入数据库(如我的数据库中存在的电子邮件)时收到this image之类的警报,当我按下sumbit按钮时会出现警报。提前致谢。 :d

这是我的create_acc.html

<form action="create_acc.php" method="POST" id="fieldform">
    <dl>
    <p><dt>Email Address:</dt>
    <dd>
    <input type="text" name="e-mail" id="e-mail" class="text" placeholder="Your Email will be your log in" autocomplete="off">
    </dd>
    </p>

    <p><dt>Create Password:</dt>
    <dd>
    <input type="password" name="password" id="password" class="text" placeholder="Remember your password" autocomplete="off">
    </p>
    <p>
    <p><dt>Your Complete name:</dt>
    <dd>
    <input type="text" name="name" id="name" class="text" placeholder="Your Complete name" autocomplete="off">
    </p>
    <p>
    <dt>
    <input type="submit" value="Submit">
    </dt>
    </p>
    </dl>
</form>

这是我的create_acc.php

<?php
session_start();
$email = $_POST['e-mail'];
$name = $_POST['name'];
$pass = $_POST['password'];

$hash = hash('sha256',$pass);

function createSalt(){
    $text = md5(uniqid(rand(), true));
    return substr($text,0,3);
}

$salt = createSalt();
$pass = hash('sha256',$salt.$hash);

$conn = mysqli_connect('localhost','root','','mydb');

$email = mysqli_real_escape_string($conn,$email);

$query = "INSERT INTO customers(Email,Password,Name,salt) VALUES('$email','$pass','$name','$salt')";

mysqli_query($conn,$query);

mysqli_close($conn);

header('Location: index.php');
?>

1 个答案:

答案 0 :(得分:0)

您可以使用ajax执行此操作。当用户提交表单时,您会将带有表单数据的ajax请求发送到您的php脚本,然后脚本将使用您用来确定是否应显示警报的值进行响应,这是使用jquery的基本示例:

$(document).ready(function() {
  // catch submit events for your form
  $('#your-form-id').submit(function() {
    // make an ajax request to your validation script
    $.ajax{(
      url:'create_acc.php',
      type:'POST',
      data:$(this).serialize(),
      dataType:'json',
      success:function(response) {
        if(!response.success) {
          alert('Something went wrong!');
        }
      }
     });
     return false;
   });
  }); 

然后在你的php脚本中返回一个代码告诉客户端它是怎么回事:

  // create_acc.php
  // I assume the form only has one value 'email'
  $success = false;
  if(isset($_POST['email'])) {
    // here you would check if the email already
    // exists in the database
    $query = "SELECT * FROM <table> WHERE email = ?";
    $stmt = $con->prepare($query);
    $stmt->bind_param('s', $_POST['email']);
    // execute the query and check if a row was returned
  }
  // if everything went fine you should change success to true

  // return json response to client
  $response = array('success' => $success);
  print json_encode($response);
  exit;