简体   繁体   English

PHP注册表格未处理AJAX数据

[英]PHP Registration Form not processing AJAX data

I may be being stupid, but I am trying to process a registration form using an AJAX call to a PHP page. 我可能很愚蠢,但是我正在尝试使用对PHP页面的AJAX调用来处理注册表。 My PHP page is working perfectly on it's own, but when I try to post the form data to the PHP page through AJAX nothing happens. 我的PHP页面本身可以完美运行,但是当我尝试通过AJAX将表单数据发布到PHP页面时,没有任何反应。

This is my AJAX call: 这是我的AJAX呼叫:

$(document).ready(function ($) {    

$("#register").submit(function(event) {
            event.preventDefault();
                $("#message").html('');
                var values = $(this).serialize();
                    $.ajax({
                    url: "http://cs11ke.icsnewmedia.net/DVPrototype/external-data/register.php",
                    type: "post",
                    data: values,
                    success: function (data) {
                    $("#message").html(data);
                    }
                    });
                }); 

});

This is the form: 形式如下:

<div id="registerform">
    <form method='post' id='register'>
        <h3>Register</h3>
        <p>Fill in your chosen details below to register for an account</p>
        <p>Username: <input type='text' name='username' value='' /><br />
           Password: <input type='password' name='password' ><br />
           Repeat Password: <input type='password' name='repeatpassword'></p>
           <input name='submit' type='submit'  value='Register' >
           <input name='reset' type='reset' value='Reset'><br /><br />
     </form>      
           <div id="message"></div>                          
</div>

And this is my PHP page: 这是我的PHP页面:

<?php function clean_string($db_server = null, $string){
        $string = trim($string);
        $string = utf8_decode($string);
        $string = str_replace("#", "&#35", $string);
        $string = str_replace("%", "&#37", $string);
        if (mysqli_real_escape_string($db_server, $string)) {
            $string = mysqli_real_escape_string($db_server, $string);
        }
        if (get_magic_quotes_gpc()) {
            $string = stripslashes($string);
        }
        return htmlentities($string);
    }

    function salt($string){
        $salt1 = 'by*';
        $salt2 = 'k/z';
        $salted = md5("$salt1$string$salt2");
        return $salted;
    }
?>

<?php
//form data                             
$submit = trim($_POST['submit']);
$username = trim($_POST['username']);
$password = trim($_POST['password']);
$repeatpassword = trim($_POST['repeatpassword']);
// create variables
$message = '';
$s_username = '';

    //connect to database

{databaseconnection} {数据库连接}

    $db_server = mysqli_connect($db_hostname, $db_username, $db_password);
    $db_status = "connected";
    if(!$db_server){

        //error message
        $message = "Error: could not connect to the database.";
    }else{
        $submit = clean_string($db_server, $_POST['submit']);
        $username = clean_string($db_server, $_POST['username']);
        $password = clean_string($db_server, $_POST['password']);
        $repeatpassword = clean_string($db_server, $_POST['repeatpassword']);

                //check all details are entered
                if ($username&&$password&&$repeatpassword){

                    //check password and repeat match
                    if ($password==$repeatpassword){

                        //check username is correct length
                        if (strlen($username)>25) {
                            $message = "Username is too long, please try again.";                           
                        }else{
                            if (strlen($password)>25||strlen($password)<6) {

                                //check password is correct length
                                $message = "Password must be 6-25 characters long, please try again.";                              
                            }else{
                                mysqli_select_db($db_server, $db_database);

                                // check whether username exists
                                $query="SELECT username FROM users WHERE username='$username'";
                                $result= mysqli_query($db_server, $query);
                                if ($row = mysqli_fetch_array($result)){
                                    $message = "Username already exists. Please try again.";
                                }else{

                                    //insert password
                                    $password = salt($password);
                                    $query = "INSERT INTO users (username, password) VALUES ('$username', '$password')";
                                    mysqli_query($db_server, $query) or die("Registration failed. ". 
                                    mysqli_error($db_server));
                                    $message = "Registration successful!";
                                }
                            }
                        }
                    }else{
                        $message = "Both password fields must match, please try again.";
                    }
                }else{
                    $message = "You must fill in all fields, please try again.";    
                }
            }   

echo $message;          
mysqli_close($db_server);

?>

Apologies for all the code. 对所有代码表示歉意。 I feel I may be making a stupid mistake but I don't know why the data isn't being posted or returned. 我觉得自己可能犯了一个愚蠢的错误,但是我不知道为什么数据没有被发布或返回。

Thanks in advance! 提前致谢!

Notice: This is more a comment than an answer but this is more readable since it includes code. 注意:这不是评论,而是答案,但由于它包含代码,因此更具可读性。

== EDIT == ==编辑==

I Checked your code on http://cs11ke.icsnewmedia.net/DVPrototype/#registerlogin , your form doesn't have a id assigned to it 我在http://cs11ke.icsnewmedia.net/DVPrototype/#registerlogin上检查了您的代码,您的表单没有分配ID

First: use your console...do you see an XMLHTTPREQUEST in your console? 首先:使用控制台...在控制台中看到XMLHTTPREQUEST吗? What are the responses/headers etc? 有什么回应/标题等? I can't stress this enough: use your console and report back here!!! 我对此压力不足:请使用您的控制台并在此处报告!!!

Next up the overly complicated ajax call...dumb it down to: 接下来处理过于复杂的ajax调用...将其哑化为:

$('#register').submit(function(){
    $('#message').html('');

    $.post("http://cs11ke.icsnewmedia.net/DVPrototype/external-data/register.php",
        $(this).serialize(),
        function(response){
            console.log(response);
            $('#message').html(response);
        }
    );

    return false;
});

In your PHP put this on top to check whether anything at all came through: 在您的PHP中,将其放在最上方以检查是否完全通过了以下操作:

die(json_encode($_POST));

请使用Firebug或任何其他工具检查AJAX脚本是否被调用,其答案是什么以及脚本中是否有错误。

My form is not submitting data to my database. 我的表单未将数据提交到数据库。 This is the PHP code: 这是PHP代码:

<?php require 'core.inc.php'; ?>
<?php require 'connection.inc.php'; ?>
<?php 

if(isset($_POST['username']) && isset($_POST['password']) && 
    isset($_POST['password_again']) && isset($_POST['firstname']) && 
    isset($_POST['surname'])){

  $username = $_POST['username'];
  $password = $_POST['password'];
  $hashed_password = sha1($password);
  $password_again = sha1('password again');
  $username = $_POST['firstname'];
  $password = $_POST['surname'];

  //check if all fields have been filled
  if(!empty($username)&& !empty($password) && !empty($password_again) && 
      !empty($firstname)&& !empty($surname)){

    if($password != $password_again){
      echo 'Passwords do not match.';
    } else {    
      //check if user is already registered;
      $query = "SELECT username FROM user WHERE username = {$username} ";
      $query_run = mysqli_query($connection, $query);

      if (mysqli_num_rows ($query_run)==1){

        echo 'User Name '.$username.' already exists.';
      } else {
        //register user
        $query = "INSERT INTO `user` VALUES ('', '".$username."', 
        '".$password_hashed."','".$firstname."','".$surname."',)";

      }

      if($query_run = mysqli_query($connection, $query)){
        header('Location: reg_succed.php');
      } else {
        echo 'Sorry we couldn\'t register you at this time. try again later';
      }
    }

  }

} else {
  echo 'All fields are required';
}   

?>

<h2>Create New User</h2>

<form id="form" action="<?php echo $current_file ?>" method="POST">
<fieldset title="Login details" id="frame"> 
<legend>USER LOGIN DETAILS</legend>
<label>User Name:</label><br/>
<input type="text" name = "username" id = "username" value="<?php if(isset($username)){ echo $username; } ?>"  maxlength="50" placeholder="Enter your Username" required/><br/>

<label>First Name:</label><br/>
<input type="text" name="firstname" id = "firstname" value="<?php if(isset($firstname)){ echo $firstname;} ?>" maxlength="50" placeholder="Enter your Firstname" required/><br/>                    
<label>Surname:</label><br/>
<input type="text" name="surname" id="surname" value="<?php if(isset($surname)) {echo $surname;} ?>" maxlength="50" placeholder="Enter your Surname" required/><br/>

<label>Password:</label><br/>
<input type="password" name="password" id="password"   maxlength="50" placeholder="Enter your Password" required/><br/>

<label>Password Again:</label><br/>
<input type="password" name="password_again" id="password again"  maxlength="50"  placeholder="Enter your Password" required/><br/>

<input type="submit" name = "register" id = "register" value="Register">
</fieldset>
</form>

connection code
<?php
require_once("constants.php");

// 1. Create a database connection
$connection = mysqli_connect(DB_SERVER,DB_USER,DB_PASS, DB_NAME);
if (!$connection) {
    die("Database connection failed: " . mysqli_error($connection));
}

// 2. Select a database to use 
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
    die("Database selection failed: " . mysqli_error($connection));

}
?>

core.inc.php code
<?php
ob_start();
session_start();
$current_file = $_SERVER['SCRIPT_NAME'];

if(isset( $_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER'])){
$http_referer = $_SERVER['HTTP_REFERER'];
}



?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM