为什么我的注册按钮会重定向到index.php?

时间:2017-04-07 04:24:57

标签: php jquery

我很困惑,我甚至无法解释我的问题。当我点击我的注册按钮时,它会重定向到index.php。它应该检查错误,而不是重定向或类似的东西。我尝试删除代码中的错误,更改ID,更改css属性。添加和删​​除JQuery。我真的不知道如何解决这个问题。

修改

在成功功能中,我尝试删除window.open(),但仍然会点击index.php重定向到#check_signup。我将在那里保留该行以显示原始代码的外观。代码不能重定向,因为代码尚未到达成功文本。

假设发生的是代码通过 check_signup.php 通过AJAX检查错误。然后该页面返回单词" success"如果代码全部正确执行。 script.js 中的代码然后检查单词" success"在重定向到index.php之前。

我尝试删除了ID #check_signup,并且页面没有重定向。当我尝试点击#check_signup时提醒页面时,它不起作用。因此,在单击元素注册之前,页面将重定向。

这是代码:

的script.js

$(document).ready(function() {

    /* Sign Up Page */

  $("#check_signup").click(function() {
    var username_signup = $("#signup_container input[key='username_signup']").val();
    var email_signup = $("#signup_container input[key='email_signup']").val();
    var password_signup = $("#signup_container input[key='password_signup']").val();

     $.ajax({
  type: "POST",
  url: "check_signup.php",
  data: {username: username_signup, email: email_signup, password: password_signup},
  success: function(data){
    if(data.indexOf("Success")) {
      window.open("index.php","_self");
    } else {
     $("#signup_container").html(data);
    }
  }
});

  });
});

signup.php

<?php

  require "connect.php";

?>

<!DOCTYPE html>
<html>
  <head>
    <title> Website </title>

    <!-- CSS Files -->
    <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
    <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="css/styles.css">

    <!-- JS Files -->
    <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
    <script src='js/jquery.countdown.js'></script>
    <script src='js/script.js'></script>
  </head>

  <body>

    <!-- Navigation -->
   <nav class="navbar navbar-default navbar-fixed-top">
    <div class="container">

        <div class="navbar-brand">
            <a href="index.php"> <img src="http://logos-download.com/wp-content/uploads/2016/06/Udemy_logo.png" class="img-responsive" id="logo"> </a>
        </div>

        <div class="pull-right">
              <a href='login.php'> <button type="button" class="btn btn-danger" id="login_button">Login</button> </a>
        </div>

    </div>
</nav>
    <!-- End of Navigation col-md-3 portfolio-item -->


<div class="container">
    <div class="row vertical-offset-100">
        <div class="col-md-4 col-md-offset-4" id='login_form'>
            <div class="panel panel-default">
                <div class="panel-heading">
                    <h3 class="panel-title">Join for Free</h3>
                </div>
                <div class="panel-body" id='signup_container'>
                    <form>
                    <fieldset>
                      <div class="form-group">
                            <input class="form-control" placeholder="Username" name="username" type="text" key='username_signup' autocomplete="off">
                        </div>

                        <div class="form-group">
                            <input class="form-control" placeholder="Email" name="email" type="text" key='email_signup' autocomplete="off">
                        </div>

                        <div class="form-group">
                            <input class="form-control" placeholder="Password" name="password" type="password" value="" key='password_signup' autocomplete="off">
                        </div>

                        <input class="btn btn-lg btn-primary btn-block" type="button" value="Sign Up Now" id='check_signup'>
                    </fieldset>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- End of Login Page -->

check_signup.php

   <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
     <script src='js/script.js'></script>

<?php

require "connect.php";

error_reporting(0);

// Variables
$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$md5_password = md5($password);

// Username

echo "  <form>
                    <fieldset>";

if(strlen($username) < 3) {
  echo "<div class='form-group has-error'>
  <label class='control-label' for='inputError1'>Username requires 3 characters</label>
  <input type='text' class='form-control' id='inputError1' key='username_signup' value='$username'>
</div>";
} else {
  $username_count++;
}

if(strlen($username) > 25) {
  echo "<div class='form-group has-error'>
  <label class='control-label' for='inputError1'>The username is limited to 25 characters</label>
  <input type='text' class='form-control' id='inputError1' value='$username' key='username_signup'>
</div>";
} else {
  $username_count++;
}

$check_user = $db->query("SELECT * FROM users WHERE username='$username'");
$num_user = $check_user->num_rows;

if($num_user == 0) {
  $username_count++;
} else {
   echo "<div class='form-group has-error'>
  <label class='control-label' for='inputError1'>Username Taken </label>
  <input type='text' class='form-control' id='inputError1' value='$username' key='username_signup'>
</div>";
}

if($username_count == 3) {
  echo "<div class='form-group'>
                           <input class='form-control' placeholder='Username' name='username' type='text' id='username_signup' value='$username' key='username_signup'>
                        </div>";
}

// End of Username

// Email

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    // invalid emailaddress
    echo "<div class='form-group has-error'>
  <label class='control-label' for='inputError1'>Invalid Email</label>
  <input type='text' class='form-control' id='inputError1' value='$email' key='email_signup'>
</div>";
} else {
  $email_count++;
}

$check_email = $db->query("SELECT * FROM users WHERE email='$email'");
$num_email = $check_email->num_rows;

if($num_email == 0) {
  $email_count++;
} else {
   echo "<div class='form-group has-error'>
  <label class='control-label' for='inputError1'>Email Taken</label>
  <input type='text' class='form-control' id='inputError1' value='$email' key='email_signup'>
</div>";
}

if($email_count == 2) {
  echo "<div class='form-group'>
                           <input class='form-control' placeholder='Username' name='username' type='text' id='username_signup' value='$email' key='email_signup'>
                        </div>";
}

// End of Email

// Password

if(strlen($password) < 6) {
  echo "<div class='form-group has-error'>
  <label class='control-label' for='inputError1'>Password requires 6 characters</label>
  <input type='password' class='form-control' id='inputError1' value='$password' key='password_signup'>
</div>";
} else {
  $password_count++;
  echo "<div class='form-group'>
                           <input class='form-control' placeholder='Password' name='password' type='password' id='password_signup' value='$password' key='password_signup'>
                        </div>";
}

echo "<input class='btn btn-lg btn-primary btn-block' type='button' value='Sign Up Now' id='check_signup'>
                    </fieldset>
                    </form>";

// End of Password

if($username_count == 3 && $email_count == 2 && $password_count == 1) {
  $db->query("INSERT INTO users VALUES('','$username','$email','$md5_password')");

  $findID = $db->query("SELECT * FROM users WHERE username='$username' AND password='$md5_password'");
  $fetchID = $findID->fetch_object();
  $real_id = $fetchID->id;

  session_start();
  $_SESSION["username"] = $real_id;

    echo "Success";

}

?>

我知道这是很多代码。我已经尝试了所有我能想到的东西。我确定这是一个简单的错误,但我不知道如何修复此代码。我试图修复代码以检查错误,而不是重定向回index.php。

1 个答案:

答案 0 :(得分:1)

我之前发布了这个,以帮助其他人。所以也许这会让你走上正确的道路......在你认为合适的时候修补它,我希望它有所帮助! : - )

请注意以下几点: 1.我没有使用表单标签。这消除了表单提交和重定向某些浏览器问题的正常操作。这也意味着您必须自己处理重定向。 2.验证字段在PHP中完成,并且在访问任何数据库之前也完成。这有助于限制对数据库的调用并节省资源。 我正在使用mysqli和准备好的声明。这是出于安全目的,在编码ANYTHING时应该是标准做法。 我正在检查大于和小于相同if字符的字符数。保持代码清洁。 我完成这些工作后,我正在关闭我的联系。这既适用于安全性,也适用于节省服务器上的资源。这是最好的做法。 6.我在整个代码中使用异常,必要时抛出异常。这有助于通过限制必须执行的if / else if / else循环次数来保持代码清洁。

//////////////// FORM HTML ////////////////

<div class="form" id="signupform">

    <fieldset>

        <div class="form-group">

            <input class="form-control" placeholder="Username" id="user" type="text" key='username_signup' autocomplete="off">

        </div>

        <div class="form-group">

            <input class="form-control" placeholder="Email" id="email" type="email" key='email_signup' autocomplete="off">

        </div>

        <div class="form-group">

            <input class="form-control" placeholder="Password" id="pass" type="password" key='password_signup' autocomplete="off">

        </div>

        <input class="btn btn-lg btn-primary btn-block" type="button" value="Sign Up Now" id='signupbutton'>

    </fieldset>

</div>



//////////////// JQUERY/AJAX CODE ////////////////

<script>

    // Call form submit from on click action
    $('#signupbutton').on('click', function(e){

        // Prevent onclick even from propagating
        e.stopPropagation();

        // Set variables from form inputs
        var user = $("#user").val(),
            email = $('#email').val(),
            pass = $('#pass').val();

        // Initiate ajax call to external script
        $.ajax({
            type: 'POST',
            url: 'postpage.php',
            data: {
                user    : user,
                email   : email,
                pass    : pass
            },
            success: function(data){
                if(data.indexOf("Success")) {

                    // Successful response
                    var successmessage = data;
                    alert(successmessage);

                }
                else {

                    // Error response
                    var errormessage = data;
                    alert(errormessage);

                }
            }
        });

    });

</script>



//////////////// PAGE TO POST AJAX TOO ////////////////

<?

# Start your try/catch statement to check for thrown exceptions (error messages)
try {

    # Check for $_POST to initiate script
    if( !empty($_POST) ){

        # Loop through each post value
        foreach( $_POST as $key => $val ){

            # Check if each post value is empty and throw and exception and if not set it as a variable
            if( !empty($val) ){

                ${$key} = trim($val);

            }

            else {

                # Throw Exception (error message)
                throw new Exception("Error, missing fields.");

            }

        }

        # Check if $user is alphanumeric and is at least 3 to 25 characters
        if( !ctype_alnum($user) || strlen($user) < 3 || strlen($user) > 25 ){

            # Throw Exception (error message)
            throw new Exception("Error, username must be alphanumeric and at least 3 to 20 characters.");

        }

        # Check if $email is valid
        if( filter_var($email, FILTER_VALIDATE_EMAIL) ){

            # Throw Exception (error message)
            throw new Exception("Error, invalid email.");

        }

        # Check if $pass is at least 6 to 25 characters
        if( strlen($pass) < 6 || strlen($pass) > 25 ){

            # Throw Exception (error message)
            throw new Exception("Error, password must be at least 6 to 25 characters.");

        }

        # Connection data
        $servername = "";
        $username = "";
        $password = "";
        $dbname = "";

        # Make MYSQLI Connection
        $mysqli = new mysqli($servername, $username, $password, $dbname);

        if ( $mysqli->connect_errno ) {

            # Throw connections error message
            throw new Exception("Error, could not connect to database.");

        }

        # Prepare your query for execution
        $stmt = $mysqli->prepare("SELECT `username`,`email` FROM `users` WHERE `username` = ? OR `email` = ?");

        # Bind the two parameters to your statement
        $stmt->bind_param("ss", $user, $email);

        if ( $stmt === false ) {

            # Throw Exception (error message)
            throw new Exception("Error, could not process data submitted.");

        }

        # Excecute your query
        $stmt->execute();

        if ( $stmt === false ) {

            # Throw Exception (error message)
            throw new Exception("Error, count not execute database query.");

        }

        # Bind the results to a variable
        $stmt->bind_result($users);

        # Fetch your data from results
        while($stmt->fetch()){

            $foundusers = $users;

        }

        if ( $stmt === false ) {

            # Throw Exception (error message)
            throw new Exception("Error, could not get results from database.");

        }

        # Set counters for username and emails found
        $usernames = 0;
        $emails = 0;

        # Loop through each database entry retrieved and check for matching usernames and emails
        foreach( $foundusers as $thisuser ){

            if( !empty($thisuser["email"]) && $thisuser["email"] == $email ){

                # Add 1 to the $emails counter
                $emails++;

            }

            if( !empty($thisuser["username"]) && $thisuser["username"] == $user ){

                # Add 1 to the $usernames counter
                $usernames++;

            }

        }

        # close your statement
        $stmt->close();
        $thread = $mysqli->thread_id;
        $mysqli->kill($thread);


        #Check if matching usernames OR emails were found
        if( $usernames > 0 || $emails > 0 ){

            # Check if $usernames and $emails counter is great than 0
            if( $usernames >= 1 && $emails >= 1 ){

                # Throw Exception (error message)
                throw new Exception("Error, username & email are taken.");

            }

            # Check if $usernames counter is great than 0
            if( $usernames >= 1 ) {

                # Throw Exception (error message)
                throw new Exception("Error, username is taken.");

            }

            # Check if $emails counter is great than 0
            if( $emails >= 1 ) {

                # Throw Exception (error message)
                throw new Exception("Error, email is taken.");

            }

        }

        # Make MYSQLI Connection
        $mysqli = new mysqli($servername, $username, $password, $dbname);

        if ( $mysqli->connect_errno ) {

            # Throw connections error message
            throw new Exception("Error, could not connect to database.");

        }

        # Prepare your query for execution
        $stmt = $mysqli->prepare("INSERT INTO `users` ( `username`, `email`, `password`) VALUES (?, ?, ?)");

        # Bind the two parameters to your statement
        $stmt->bind_param("sss", $user, $email, $pass);

        if ( $stmt === false ) {

            # Throw Exception (error message)
            throw new Exception("Error, could not process data submitted.");

        }

        # Excecute your query
        $stmt->execute();

        if ( $stmt === false ) {

            # Throw Exception (error message)
            throw new Exception("Error, count not execute database query.");

        }

        # close your statement
        $stmt->close();
        $thread = $mysqli->thread_id;
        $mysqli->kill($thread);

        # Echo success message
        echo "Success, account hase been created!";

    }
    else {

        # Throw Exception (error message)
        throw new Exception("Error, could not initiate script.");

    }

}

# Catch any exceptions thrown and output the error
catch( Exception $e ) {

    # Check if statement is still open and close it
    if($stmt){
        $stmt->close();
        $thread = $mysqli->thread_id;
        $mysqli->kill($thread);
    }

    # Echo success message
        echo $e->getMessage();

}
相关问题