2017-04-07 36 views
0

我很困惑,我甚至不能很好地解釋我的問題。當我點擊我的註冊按鈕時,它會重定向到index.php。它應該檢查錯誤,而不是重定向或類似的東西。我試過從我的代碼中刪除錯誤,更改ID,更改CSS屬性。添加和刪​​除JQuery。我真的不知道如何解決這個問題。爲什麼我的註冊按鈕重定向到index.php?

編輯

在成功的功能,我試圖刪除window.open(),它仍然重定向到index.php#check_signup點擊。我將在那裏保留這一行,以顯示原始代碼假設的樣子。該代碼不會被重定向,因爲代碼尚未達到成功文本。

假設發生的事情是,代碼通過AJAX通過check_signup.php檢查錯誤。如果代碼全部正確執行,此頁面將返回單詞「success」。 script.js中的代碼然後在重定向到index.php之前檢查單詞「success」。

我嘗試刪除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。

+0

如果您的代碼不正確地重定向到index.php,那麼第一步是搜索代碼以查找對index.php的任何引用。你覺得'window.open(「index.php」,「_ self」);'做了什麼? – nnnnnn

+0

@nnnnnn我已經刪除了對index.php的引用,它仍然重定向到index.php。我不知道爲什麼... – user6902601

+0

@SumanDey任何幫助表示讚賞。我的頭痛得很厲害:) – user6902601

回答

1

我之前發佈了這個幫助其他人。所以,也許這會讓你走上正確的道路......當你認爲合適的時候用它來修補它,我希望它有幫助! :-)

注意幾件事: 1.我沒有使用表格標籤。這消除了表單的正常操作,並通過某些瀏覽器重定向問題。這也意味着你必須自己處理重定向。 2.驗證字段在PHP中完成,並且在訪問任何數據庫之前也完成。這有助於限制對數據庫的調用並節省資源。 3.我正在使用mysqli和準備好的語句。這是出於安全目的,並且在編碼ANYTHING時應該是標準做法。 4.我正在查看大於和小於相同的字符數。保持您的代碼清潔。 5.我完成他們後,我正在關閉我的連接。這是爲了安全和在服務器上節省資源。這是最好的做法。 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(); 

} 
0

的preventDefault();`這樣

$("#check_signup").click(function(event) { 
    event.preventDefault(); 
    //rest of your code 
    ... 
} 

希望這將幫助你click事件之後。

+0

感謝您的回答。它現在不重定向,但它現在不會做任何事情...... – user6902601

+0

有問題的按鈕是'type =「按鈕」',所以它沒有任何默認行爲來取消。 – nnnnnn

+0

他通過ajax提交表單,因此preventDefault不會爲他做任何事情......從技術上講,

標記是無用的和不相關的。 –