javascript - 使用PHP与MVC架构的AJAX mysqli交互

标签 javascript php jquery ajax mysqli

今天我遇到了另一个与 AJAX 相关的错误。

我假装使用ajax和php构建一个用户注册系统,采用mvc架构。

我构建了一个没有ajax的登录系统,工作没有任何问题,各方之间有连接和交互。

我几乎可以肯定错误是由 JS 文件引起的,我已经通过 JSHint 传递了我的文件来检测错误,但没有发现任何错误,可能是代码逻辑中存在一些错误。

首先,在发布我的代码之前,我将向您展示我的数据文件结构,以免您在考虑路径时感到头痛:

Data Tree

我将把代码粘贴到这里,然后我将对每段代码进行评论。

查看/register.php

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	<link rel="stylesheet" href="../css/register.css">
 	<script src="../js/valReg.js"></script>
<section class="registerPage1">
	<section class="registerPage2">
		<form method="post" action="#" onsubmit="" id="regTopfit" name="regTopfit">
			<ul>
				<input type="button" value="Full Registration" id="advReg">
				<li>Nombre:</li>
				<li><input id="i_firstname" type="text" name="firstname" placeholder="Firstname"><input id="i_lastname" type="text" name="lastname" placeholder="Lastname"></li>
				<br>
				<li><input type="text" id="i_dni" placeholder="Your ID"></li>
				<li><input id="i_username" type="text" name="username" placeholder="Username"><span id="user-result"></span></li>
				<li><input id="i_email" type="email" name="email" placeholder="Email address"></li>
				
				<span class="extraFieldsRegistration">
					<li><input type="text" id="i_phone" placeholder="Phone number"></li>
					<li><input type="text" id="i_address" placeholder="Address"></li>
					<li><input type="text" id="i_city" placeholder="City"></li>
					<li><input type="text" id="i_postal" placeholder="Postal Code"></li>
					<li><input type="text" id="i_province" placeholder="Province"></li>
					<li><input type="text" id="i_creditcard" placeholder="Credit Card number"></li>
				</span>
				
				<li><div id="regMailError">Debes introducir una dirección de correo electrónico válida.</div></li>
				<li>Crear contraseña:</li>
				
				<li><input id="i_pass1"  type="password" name="pass1" placeholder="6-20 caracteres" ></li>
				
				error<li><div id="regPLenError">Debes introducir una dirección de correo electrónico válida.</div></li>
				
				<li><input id="i_pass2" type="password" name="pass2" placeholder="Repite la contraseña" ></li>
				
				error<li><div id="regPMatchError">Debes introducir una dirección de correo electrónico válida.</div></li>
				
				<li><input type="checkbox" name="offers" value="Yes">Quiero recibir las últimas novedades de <a href="#">TopFIT</a></li>
				
				<li><input id="i_conditions" type="checkbox" name="conditions" value="accepted" >He leído y acepto la <a href="#">política de privacidad</a>.</li>
				
				error<li><div id="regCondError">Debes introducir una dirección de correo electrónico válida.</div></li>
				
				<li><input type="button" id="register" value="Crea tu cuenta"></li>
				<li><span id="result"></span></li>
			</ul>
		</form>
	</section>
</section>
</body>
</html>

关于景色没什么好说的。

Controller /register.php

<?php 
//REGISTER controller 

require "../model/backend.php";

$username = $_POST["#i_username"];
$email  =  $_POST["#i_email"];
$password = $_POST["#i_pass1"];
$firstname = $_POST["#i_firstname"];
$lastname = $_POST["#i_lastname"];
$dni = $_POST["#i_dni"];
$phone = $_POST["#i_phone"];
$address = $_POST["#i_address"];
$city = $_POST["#i_city"];
$postal = $_POST["#i_postal"];
$province = $_POST["#i_province"];
$creditcard = $_POST["#i_creditcard"];

$dbcom = new dbInteraction;
$dbcom->register($firstname, $lastname, $email, $dni, $phone, $address, $city, $postal, $province, $creditcard, $username, $password);
$dbcom->conclose();
?>

在这种情况下,如您所见,我选择输入的值,然后调用我的注册函数,传递所有参数来执行注册。我认为这里的一切也很酷。

model/backend.php

<?php 
//model!
class dbInteraction{

    private $connection;
    private $server = "127.0.0.1";
    private $s_user = "root";
    private $s_password ="";
    private $db = "youtube";
    private $dni;
    private $firstname;
    private $lastname;
    private $username;
    private $password;
    private $phone;
    private $address;
    private $city;
    private $postal;
    private $province;
    private $creditcard;

    public function __construct(){
        $this->connection = new mysqli($this->server, $this->s_user, $this->s_password, $this->db); 

        if($this->connection->connect_errno){
        //  echo $db->connect_error;
            die('Sorry, we are having problems.');

        }
    }

    public function conclose(){
        $this->connection->close();
    }

    public function login($user, $password){
        $this->user = $username;
        $this->password = $password;

        $query = "SELECT id, firstname, lastname, password FROM people WHERE username = '".$this->user."' AND password = '".$this->password."' ";

        $myquery = $this->connection->query($query);

        if ($row = mysqli_fetch_array($myquery)){// or die($this->connection->error)) {
            session_start();

            $_session['id'] = $row['id'];
            $_session['firstname'] = $row['firstname'];
            $_session['lastname'] = $row['lastname'];

            echo 'Signed in.' , '<br>';

            echo 'Welcome' , $_session['firstname'];
        }else{
            echo 'Check your data and try again.';
        }
    }

    public function register($firstname, $lastname, $email, $dni, $phone, $address, $city, $postal, $province, $creditcard, $username, $password){
        $this->firstname = $firstname;
        $this->lastname = $lastname;
        $this->email = $email;
        $this->dni = $dni;
        $this->phone = $phone;
        $this->address = $address;
        $this->city = $city;
        $this->postal = $postal;
        $this->province = $province;
        $this->creditcard = $creditcard;
        $this->username = $username;
        $this->password = $password;

        $query = "INSERT INTO users (username, email, password, firstname, lastname, dni, phone, address, city, postal, province, creditcard) VALUES ('$username','$email','$password', '$firstname', '$lastname', '$dni', '$phone', '$address', '$city', '$postal', '$province', $creditcard)";

        $myquery = $this->connection->query($query);

        if ($row = mysqli_fetch_array($myquery)) {
            session_start();
            $_session['id'] = $row['id'];
            $_session['firstname'] = $row['firstname'];
            $_session['lastname'] = $row['lastname'];

            echo 'You have been correctly registered. Welcome to TopFIT ', $_session['firstname']; 
        }else{
            echo 'Something went wrong.';
        }

    }

    public function newPassword($email){
        $this->email = $email;
    }

}

我们必须关注注册函数,它看起来很简单。我认为我很确定我在那里使用的语法。

JS文件

$(document).ready(function(){
  
  var showFull = $(".extraFieldsRegistration");
  var fullReg = $("#advReg")
  fullReg.click(function(){
    showFull.css('display','inline');
  });

  $("#register").click(function(){
    var mailValue = $("#i_email").val();
    var usernameValue = $("#i_username").val();
    var passwordValue = $("#i_pass1").val();
    var passwordValue2 = $("#i_pass2").val();
    var conditionsValue = $("#i_conditions").val();

    var fnameValue = $("#i_firstname").val();
    var lnameValue = $("#i_lastname").val();
    var dniValue = $("#i_dni").val();
    var phoneValue = $("#i_phone").val();
    var addrValue = $("#i_address").val();
    var cityValue = $("#i_city").val();
    var postalValue = $("#i_postal").val();
    var provValue = $("#i_province").val();
    var ccValue = $("#i_creditcard").val();

    var __mailError = document.getElementById('regMailError'); 
    var __passLenError = document.getElementById('regPLenError');
    var __passMatchError = document.getElementById('regMatchError');
    var __condError = document.getElementById('regCondError');

 

    if (mailValue === '' || passwordValue === '' || passwordValue2 === '' || usernameValue === ''){
      alert('completa todos los campos');
    }else{
      if (passwordValue != passwordValue2){
        alert('contraseñas distintas');
      }else{
        if (document.getElementById('conditions').checked){
          $.ajax({
            type: "POST",
            url: "../controller/register.php",
            data: {
              username: usernameValue,
              email: mailValue,
              password: passwordValue,
              firstname: fnameValue,
              lastname: lnameValue,
              dni: dniValue,
              phone: phoneValue,
              address: addrValue,
              city: cityValue,
              postal: postalValue,
              province: provValue,
              creditcard: ccValue
            },
            success: function(msg){
              $("#result").html(msg);
            },
            error:function(){
              alert('error');
            }
          });

        }else{
          alert('Debes aceptar las condiciones');
        }
      }
    }
  }); //click del register
}); //document ready

好吧,我确实认为这里有错误。

一开始,有一段代码假装修改 View 范围的属性,将该属性(显示)从无更改为内联。

我之前在其他文件和函数中使用过这段代码,它工作正常,现在我不知道为什么它不起作用。

然后是表单验证器,之后,如果一切顺利,在 if 内,我尝试与其他 mvc 文件进行通信,传递应记录到我的数据库的参数。

你会注意到有很多未使用的变量,我知道,我将使用这些变量来修改 View 中一些div的css(如果出现错误),但我决定使用警告调试。所以你看到alert的地方就会有一个css修饰符。

我认为一切都有逻辑,但尽管我的东西,它不起作用。

我一直在寻找解决方案,我发现使用 JSON 可能会节省时间、代码和问题,但我必须在没有 json 的情况下做到这一点,至少现在是这样。

你发现错误了吗?您有更好的想法来构建这个系统吗?

一如既往,我会感谢您的帮助。

最佳答案

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>

     <!-- ADD / LOAD JQUERY HERE with the correct path -->
  
 	<script src="../js/jquery.js"></script>
 
</head>
<body>
	<link rel="stylesheet" href="../css/register.css">
  <script src="../js/valReg.js"></script>
<section class="registerPage1">
	<section class="registerPage2">
		<form method="post" action="#" onsubmit="" id="regTopfit" name="regTopfit">
			<ul>
				<input type="button" value="Full Registration" id="advReg">
				<li>Nombre:</li>
				<li><input id="i_firstname" type="text" name="firstname" placeholder="Firstname"><input id="i_lastname" type="text" name="lastname" placeholder="Lastname"></li>
				<br>
				<li><input type="text" id="i_dni" placeholder="Your ID"></li>
				<li><input id="i_username" type="text" name="username" placeholder="Username"><span id="user-result"></span></li>
				<li><input id="i_email" type="email" name="email" placeholder="Email address"></li>
				
				<span class="extraFieldsRegistration">
					<li><input type="text" id="i_phone" placeholder="Phone number"></li>
					<li><input type="text" id="i_address" placeholder="Address"></li>
					<li><input type="text" id="i_city" placeholder="City"></li>
					<li><input type="text" id="i_postal" placeholder="Postal Code"></li>
					<li><input type="text" id="i_province" placeholder="Province"></li>
					<li><input type="text" id="i_creditcard" placeholder="Credit Card number"></li>
				</span>
				
				<li><div id="regMailError">Debes introducir una dirección de correo electrónico válida.</div></li>
				<li>Crear contraseña:</li>
				
				<li><input id="i_pass1"  type="password" name="pass1" placeholder="6-20 caracteres" ></li>
				
				error<li><div id="regPLenError">Debes introducir una dirección de correo electrónico válida.</div></li>
				
				<li><input id="i_pass2" type="password" name="pass2" placeholder="Repite la contraseña" ></li>
				
				error<li><div id="regPMatchError">Debes introducir una dirección de correo electrónico válida.</div></li>
				
				<li><input type="checkbox" name="offers" value="Yes">Quiero recibir las últimas novedades de <a href="#">TopFIT</a></li>
				
				<li><input id="i_conditions" type="checkbox" name="conditions" value="accepted" >He leído y acepto la <a href="#">política de privacidad</a>.</li>
				
				error<li><div id="regCondError">Debes introducir una dirección de correo electrónico válida.</div></li>
				
				<li><input type="button" id="register" value="Crea tu cuenta"></li>
				<li><span id="result"></span></li>
			</ul>
		</form>
	</section>
</section>
</body>
</html>

关于javascript - 使用PHP与MVC架构的AJAX mysqli交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33450381/

相关文章:

javascript - 切换http状态码

javascript - Highcharts:获取 x 轴显示图例

php - 我的 htaccess 文件不断出现 404 错误

javascript - jQuery 在页面上显示输入的文本

javascript - 自动登录 Zoho 应用程序

javascript - 向 Chrome 扩展程序添加禁用按钮

PHP scandir 递归

php - foreach 循环和 jQuery

jquery - jQuery 中的自动完成功能使用什么事件

javascript - 添加 preventDefault() 和 stopPropagation()