如何在同一页面而不是新页面上显示错误

时间:2016-03-26 19:40:50

标签: php

大家好,所以我创建了一个简单的登录表单,但是我的问题是当我弹出错误时,它们弹出不同的页面而不是同一页面。我希望他们在提交按钮下方弹出一个简单的<p>标签,我将在css中编辑并将其设为红色等。但此时它所做的只是打开一个新页面并显示错误。

PHP:

    ?php
include 'init.php';
function sanitize($data){
    return mysql_real_escape_string($data);
}
//check if user exists
function user_exists($email){
        $email = sanitize($email);
        return (mysql_result(mysql_query("SELECT COUNT(ID) FROM register WHERE email = '$email'"),0) == 1)? true : false;
}
//check if user has activated account
function user_activate($email){
        $email = sanitize($email);
        return (mysql_result(mysql_query("SELECT COUNT(ID) FROM register WHERE email = '$email' AND active =1"),0) == 1)? true : false;
}
function user_id_from_email($email){
    $email = sanitize($email);
    return (mysql_result(mysql_query("SELECT id FROM register WHERE email = '$email'"),0,'id'));
}
function login($email,$password){
    $user_id = user_id_from_email($email);
    $email = sanitize($email);
    $password = md5($password);

    return (mysql_result(mysql_query("SELECT COUNT(id) FROM register WHERE email = '$email' AND password ='$password'"),0) == 1)? $user_id : false;
}
if(empty($_POST)=== false){
    $email = $_POST['email'];   
    $password = $_POST['password'];
}
if(empty($email)|| empty($password) === true){
    $errors[] = "You must enter a username and a password";  
}
else if(user_exists($email) === false){
    $errors[] = "Email address is not registered";   
}
else if(user_activate($email) === false){
    $errors[] = "You haven't activated your account yet";   
}
else{
    $login = login($email, $password);
    if($login === false){
        $errors[] = "email/password are incorrect";
    } else {
        $_SESSION['user_id'] = $login;
        header('Location: home.php');
        exit();
    }
}
print_r($errors);
    ?>

我尝试过一个简单的事情; echo"<script>alert('Username or password is incorrect!')</script>";但是这会弹出一个弹出窗口,我想要的是一个显示在页面上的实际p标签,而不是一个框。

2 个答案:

答案 0 :(得分:1)

如果可以使用:

echo"<script>alert('Username or password is incorrect!')</script>";

然后你可以定义一个这样的函数 -

function appendHtml(el, str) {
  var div = document.createElement('div');
  div.innerHTML = str;
  while (div.children.length > 0) {
    el.appendChild(div.children[0]);
  }
}

<script>...</script>中的任何地方。

之后,你只需要使用:

echo"<script>appendHtml(document.body, '<p style=\"backround-color: #F00;\">Username or password is incorrect!</p>');</script>";

在你的PHP脚本中!

就这么简单!

答案 1 :(得分:0)

您可以使用AJAX请求提交表单。如果出现错误,则显示错误而不重新加载页面。例如:

<script type="text/javascript">
   jQuery(document).ready(function() {
       $('#submit-button').on('click', function(e) {
            var form = $('#login-form');
            $.post(form.prop('action'), form.serialize(), function(response) {
                if (response.error) {
                    // show the error wherever you want
                }
            });
            return false;
       });
   });
</script>