簡體   English   中英

我在代碼中做錯了什么? 注冊碼無效,控制台報錯

[英]What did I do wrong in the code? The registration code does not work, an error in the console

我在代碼中做錯了什么? 注冊碼不起作用,控制台報錯Data is not sent to the database

這個 script.js

$(document).ready(function(){
    $(".save").click(function(){
        let user = {
            name: $(".name").val(),
            surname: $(".surname").val(),
            age: $(".age").val(),
            gender: $(".input[name='gender']:checked").val(),
            email: $(".email").val(),
            password: $(".password").val(),
            confirm: $(".confirm").val()
        }
        $.ajax({
            type: "post",
            url: "server.php",
            data: {user: user, action: "ajax1"},
            success: function(r){
                console.log(r); 
                if(r == 1){
                    console.log(r);
                    location.reload;
                }else{
                    r = JSON.parse(r);
                if("error_name" in r){
                    $(".name").val("");
                    $(".name").attr("placeholder", r.error_name);
                }
                if("error_surname" in r){
                    $(".surname").val("");
                    $(".surname").attr("placeholder", r.error_surname);
                }
                if("error_age" in r){
                    $(".age").val("");
                    $(".age").attr("placeholder", r.error_age);
                }
                if("error_email" in r){
                    $(".email").val("");
                    $(".email").attr("placeholder", r.error_email);
                }
                if("error_password" in r){
                    $(".password").val("");
                    $(".password").attr("placeholder", r.error_password);
                }
                if("error_password" in r){
                    $(".confirm").val("");
                    $(".confirm").attr("placeholder", r.error_confirm);
                }
                }
                }
            })
        })
    })

此控制台錯誤

script.js:17 
Uncaught SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at Object.success (script.js:22:30)
    at c (jquery.min.js:2:28327)
    at Object.fireWith [as resolveWith] (jquery.min.js:2:29072)
    at l (jquery.min.js:2:79901)
    at XMLHttpRequest.<anonymous> (jquery.min.js:2:82355)

當我點擊注冊時,它給出了這個錯誤,一切似乎都很好。 我對JS有點了解

這個 server.php

<?php
    
class Controller{
    function __construct(){
        if($_SERVER['REQUEST_METHOD'] = "POST"){
            $this->db = new mysqli('localhost', 'root', 'root', 'Levon');
            if(isset($_POST['action'])){
                if($_POST['action'] == "ajax1"){
                    $this->addUser();
                }
            }
        }
    }
    
    function addUser(){
        extract($_POST['user']);
        $error = [];
        if(empty($name)){
            $error['error_name'] = "Fill the name";
        }
        if(empty($surname)){
            $error['error_surname'] = "Fill the surname";
        }
        if(empty($age)){
            $error['error_age'] = "Fill the age";
        }else if(filter_var($age, FILTER_VALIDATE_INT)){
            $error['error_age'] = "Write age correctly";
            }
        if(empty($email)){
            $error['error_email'] = "Fill the Email";
        }else if(filter_var($email, FILTER_VALIDATE_EMAIL)){
            $error['error_email'] = "Write Email correctly";
            }
        if(empty($gender)){
            $error['error_gender'] = "Select the gender";     
        }
        if(empty($password)){
            $error['error_password'] = "Select the password";
        }else if(strlen($password) < 6){
                $error['error_password'] = "Password is less than 6";
    
            }
        if(empty($confirm)){
            $error['error_confirm'] = "Fill the page";
        }
        if($password !== $confirm){
            $error['error_confirm'] = "Password didn`t metch";
        }
        if(count($error) > 0){
            print json_encode($error);
        }else{
            $hash = password_hash($password, PASSWORD_DEFAULT);
            password_verify($password, $hash);
            $this->db->query("INSERT INTO `users` (`name`, `surname`, `age`, `gender`, `email`, `password`) VALUES ('$name', '$surname', '$age', '$gender', '$email', '$password');");
            print 1;
        }
        new Controller();
    }
}

Server.php 設計不佳。 您應該始終致力於獲得一致的結果,或者在這種情況下獲得一致的輸出

代碼中包含大量注釋來描述所做的更改以及原因

<?php
    
class Controller{

    function __construct(){
        #
        # It would be better to connect once in the main process 
        # and inject the connection into objects that require it
        #
        if($_SERVER['REQUEST_METHOD'] = "POST"){
            $this->db = new mysqli('localhost', 'root', 'root', 'Levon');
            if(isset($_POST['action'])){
                if($_POST['action'] == "ajax1"){
                    $this->addUser();
                }
            }
        }
    }
    
    function addUser(){
        // this is a dangerous practice to get into
        // instead, you have a perfectly good array called $_POST, use it!
        extract($_POST['user']);

        $error = [];
        if(empty($name)){
            $error['error_name'] = "Fill the name";
        }
        if(empty($surname)){
            $error['error_surname'] = "Fill the surname";
        }
        if(empty($age)){
            $error['error_age'] = "Fill the age";
        }else if(filter_var($age, FILTER_VALIDATE_INT)){
            $error['error_age'] = "Write age correctly";
            }
        if(empty($email)){
            $error['error_email'] = "Fill the Email";
        }else if(filter_var($email, FILTER_VALIDATE_EMAIL)){
            $error['error_email'] = "Write Email correctly";
            }
        if(empty($gender)){
            $error['error_gender'] = "Select the gender";     
        }
        if(empty($password)){
            $error['error_password'] = "Select the password";
        }else if(strlen($password) < 6){
            $error['error_password'] = "Password is less than 6";
        }
        if(empty($confirm)){
            $error['error_confirm'] = "Fill the page";
        }
        if($password !== $confirm){
            $error['error_confirm'] = "Password didn`t metch";
        }
        if(count($error) > 0){
            // consistent return values, so add the status here too.
            print json_encode(['status' => 0, $error);

        }else{
            // hashing the password is GREAT, but you do then actually have to 
            // save this value to the password column in the database
            $hash = password_hash($password, PASSWORD_DEFAULT);

            // this line has no function in a create user situation
            //password_verify($password, $hash);

            // this is an SQL Injection nightmare see note at bottom
            //$this->db->query("INSERT INTO `users` (`name`, `surname`, `age`, `gender`, `email`, `password`) VALUES ('$name', '$surname', '$age', '$gender', '$email', '$password');");


            $sql = 'INSERT INTO `users` 
                            (`name`, `surname`, `age`, `gender`, `email`, `password`) 
                    VALUES (?,?,?,?,?,?)';

            $stmt = $this->db->prepare($sql);
            // bind values to the `?` parameters, note, I bound $hash and not $password
            $stmt->bind_param('ssisss', $name, $surname, $age, 
                                        $gender, $email, $hash );
            $stmt->execute();

            // this is your problem, this is not JSON you are returning
            //print 1;

            // send back a JSON structure
            echo json_encode(['status'=>1]);

        }
        // does nothing sensible here
        //new Controller(); 
    }
}

$obj = new Controller;

現在你需要修改 javascript

        $.ajax({
            type: "post",
            url: "server.php",
            // tell jquery to convert response from JSON String 
            /// to a JS Object automatically
            dataType: "json",       
            
            data: {user: user, action: "ajax1"},
            success: function(r){
                if(r.status == 1){
                    // this is your error situation
                    console.log(r);
                    location.reload;
                } else {
                . . .

SQL 注入攻擊 即使您正在逃避輸入,它也不安全! 您應該始終在MYSQLI_或 `PDO 中使用准備好的參數化語句

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM