ITPro Guy
ITPro Guy

Reputation: 187

AJAX mysqli interaction using PHP with MVC architecture

Today I'm facing another error related with AJAX.

I'm pretending to build a user registration system using ajax and php, with mvc architecture.

I built a login system without ajax and works without any problem, there is connectivity and interaction between all sides.

I'm almost sure that the error comes because of the JS file, I've passed my file through the JSHint to detect errors but nothing found, probably there is some mistake in the logic of the code.

First of all, before to post my code, I'll show you my data files structure to save you some headache thinking about the paths:

Data Tree

I'm going to paste the codes here and then I'll comment something about each piece of code.

View/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>

Nothing to say about the view.

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

In that case, as you can see, I pick the values of my inputs and then I call my register function passing all the arguments to perform the registration. I think that everything is cool here too.

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

}

We have to focus in the register function, which is that simple as it looks. I think that I'm sure of the syntax that I used there.

JS File

$(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

Ok, definitely I think that here there are mistakes.

In the beginning, there is a piece of code that pretends to modify the property of a view span, turning that property (display) from none to inline.

I previously used this code in other files and functions and it was working correctly, now I have no idea why it doesn't work.

Then there is the form validator and after that, if everything goes fine, inside an if, I try to perform the communication to the other mvc files passing the arguments that should be recorded to my db.

You'll notice that there are a lot of unused variables, I know, I'll use these ones to modify the css (in case of error) of some divs that I have in the view, but I decided to use alerts to debug. So where you see alert, there will be a css modifier.

I think that everything has logic but despite of my things, it doesn't work.

I've been looking for solutions and I saw that using JSON, probably I'll save time, code and problems but I have to do this without json, at least for now.

Did you find some error? Do you have a better idea to build this system?

As always, I'll appreciate your help.

Upvotes: 1

Views: 332

Answers (1)

Anonymous0day
Anonymous0day

Reputation: 3042

<!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>

Upvotes: 1

Related Questions