I'm playing with using AJAX to perform a simple login function using PHP. I haven't been able to get the AJAX call to successfully create an instance of the Controller class in the login handler file. I feel like I'm just not seeing something that is really basic.
I want to just say thank you in advance for any help! Also, this is not meant to be a real website or a real login script. I understand there are SO many security holes the way it is currently written. I fully intent to add all the bells, whistles, validation, etc. necessary to turn this simple code into something useful as soon as I understand the mistake.
The 4 files that should communicate with each other are as follows:
-
view/login.php
function signIn( ) { if(checkString( )) { $.ajax({ type: "POST", url: "ajax.php", data: "username=" + $("#username").val( ) + "&password=" + $("#password").val( ), dataType: "html", async: false, cache: false, success: function(result){ $("#temp_container").html(result); } }); } }
-
AJAX.php
<?php if(isset($_POST['username']) && !empty($_POST['password'])) { $controller = new IndexController( ); $result = $controller->login($_POST['username'], $_POST['password']); if($result > 0) $user_validation = array('true', 'view/chat_app.php'); else $user_validation = array('false', 'index.php?error_num=1'); echo json_encode($user_validation); } else if(isset($_POST['username']) && empty($_POST['password'])) { //notify the user they didn't put in a password } ?>
-
Controller.php
<?php include_once("model/indexModel.php"); class IndexController { public $model; public function __construct( ) { $model = new IndexModel( ); } public function login($username, $password) { $result = $model->login($username, $password); if($result >= 1) return true; else return false; } } ?>
-
Model.php
<?php include_once("config/config.php"); $db = new mysqli($GLOBALS['config']['db_host'], $GLOBALS['config']['db_username'], $GLOBALS['config']['db_password'], $GLOBALS['config']['db_name']); class IndexModel { public function login($username, $password) { global $db; $statement = $db->prepare("SELECT 1 FROM authorized_users WHERE username = ? AND password = ?"); $statement->bind_param('ss', $username, $password); $statement->execute( ); $statement->close( ); return $statement->affected_rows; } } ?>