简体   繁体   English

我在代码中做错了什么? 注册码无效,控制台报错

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

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注册码不起作用,控制台报错Data is not sent to the database

This script.js这个 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);
                }
                }
                }
            })
        })
    })

This console error此控制台错误

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)

When I click on Sign up, it gives this error, everything seems to be fine everywhere.当我点击注册时,它给出了这个错误,一切似乎都很好。 I understand a little about JS我对JS有点了解

this server.php这个 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 is poorly designed. Server.php 设计不佳。 You should always aim to have a consistent result or in this case a consistent output您应该始终致力于获得一致的结果,或者在这种情况下获得一致的输出

Lots of comments inline with the code to describe the changes made and why代码中包含大量注释来描述所做的更改以及原因

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

Now you will need to amend the javascript现在你需要修改 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 Injection Attack . SQL 注入攻击 Even if you are escaping inputs, its not safe!即使您正在逃避输入,它也不安全! You should always use prepared parameterized statements in either the MYSQLI_ or `PDO您应该始终在MYSQLI_或 `PDO 中使用准备好的参数化语句

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

相关问题 将构建数组的PHP代码转换为JS,现在highcharts不起作用-我做错了什么? - Converted PHP code that built an array to JS and now highcharts doesn't work - what did I do wrong? 此幻灯片显示代码有什么错? - What did I do wrong with this slide show code? 我知道此代码无法正常工作,为什么我找到的代码可以工作? 是什么使错误的代码错了? - I know this code does not work, why does the code that I found does? What makes the wrong code, wrong? 我的代码不起作用,怎么了? - My code does not work, what's wrong? java.lang.StringIndexOutOfBOundsException错误我做错了什么 - java.lang.StringIndexOutOfBOundsException Error what did i do wrong 我在JavaScript中做错了什么? - What did I do wrong in my javascript? jQuery Ajax-代码现在可以正常工作了吗? - JQuery Ajax - Code did work now it does not? 此代码在 else 语句中出现错误,我需要进行哪些更正才能使代码按预期工作 - this code gives an error with the else statement , what correctiions do i need to make to allow the code work as expected 我的第二个旋转木马不起作用。 我做错了什么? - My second carousel wont work. What did I do wrong? 我的D3.js代码导致将新数据添加为新图,我希望将其附加到现有图上。 我做错了什么? - My D3.js code cause new data to be added as a new graph, I want it to be appended to an existing graph. What did I do wrong?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM