dongwen1871 2017-04-07 04:24
浏览 42
已采纳

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

I'm so confused, I can't even explain my problem very well. When I click on my sign up button, it redirects to index.php. It's supposed to check for errors, not redirect or anything like that. I've tried deleting bugs from my code, changing id's, changing css properties. Adding and deleting JQuery. I really have no idea how to fix this problem.

EDIT

In the success function, I have tried to remove window.open() and it still redirects to index.php on click of #check_signup. I'm going to keep that line there to show what the original code is suppose to look like. The code isn't suppose to be redirecting because the code hasn't reached the success text yet.

What's suppose to happen is that the code checks for errors through AJAX through check_signup.php. This page then returns the word "success" if the code all executed properly. The code in script.js then check for the word "success" before redirecting to index.php.

I tried removing the id #check_signup and the page didn't redirect. When I try to make the page alert on click of #check_signup, it doesn't work. So the page is redirecting before the click element is registered.

This is the code:

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";

}

?>

I know this is a lot of code. I have literally tried everything I can think of. I'm sure it's a simple bug, but I don't know how to fix this code. I'm trying to fix the code to check for errors and not to redirect back to index.php.

  • 写回答

1条回答 默认 最新

  • doude4924 2017-04-07 05:42
    关注

    I posted this one before to help someone else out. So maybe this will get you on the correct path... Tinker with it as you see fit and I hope it helps!!! :-)

    Notice a few things: 1. I am not using form tags. Which eliminates the normal actions of a form submit and redirect issues with some browsers. This also means you have to handle the redirect on your own. 2. Validation field is done in PHP, and is also done BEFORE any databases are accessed. This helps limit the calls to your database and saves resources. 3. I am using mysqli and prepared statements. This is for security purposes and should be a standard practice when you are coding ANYTHING. 4. I am checking for number of characters greater than and less than in the same if statments. Keeps your code clean. 5. I am closing my connections after I am done with them. This is for both security and to save resources on the server. It's best practice. 6. I am using exceptions throughout my code, throwing them when necessary. This helps keeps the code clean by limiting the number of if/else if/else loops you have to do.

    //////////////// 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();
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 MATLAB怎么通过柱坐标变换画开口是圆形的旋转抛物面?
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿