Answer the question
In order to leave comments, you need to log in
Why isn't JSON data coming from the controller in AJAX?
Hello dear IT experts.
I turn to you again for help.
There is HTML code and Jquery user registration
<div id="registerBox">
<div class="menuCaption showHidden" onclick="showRegisterBox()">Регистрация</div>
<div id="registerBoxHidden">
<p>email</p>
<input type="text" id="email" name="email" value=""><br/>
<p>Пароль</p>
<input type="password" id="pwd1" name="pwd1" value=""><br/>
<p>Повторить Пароль</p>
<input type="password" id="pwd2" name="pwd2" value=""><br/><br/>
<input type="button" onclick="registerNewUser()" value="Зарегистрироватся">
</div>
</div>
function registerNewUser(){
let postData = getData('#registerBox');
console.log(postData);
$.ajax({
type:'POST',
async:true,
data:postData,
url:"/user/register/",
dataType:'json',
success:function(data){
if(data['success']){
alert('Регистрация прошла успешно!');
// блок в левом столбце
$('#registerBox').hide();
// $('#userLink').attr('href','/user/');
// $('#userLink').html(data['userName']);
// $('#userBox').show();
// страница заказа
// $('#loginBox').hide();
// $('#btnSaveOrder').show();
}
else{
alert(data['message']);
}
}
});
}
<!-- контроллер пользователей -->
<?php
//подключаем модули
include_once '../models/CategoriesModel.php';
include_once '../models/UsersModel.php';
function registerAction(){
$email = isset($_REQUEST['email'])? $_REQUEST['email']:null;
$email = trim($email);
$pwd1 = isset($_REQUEST['pwd1']) ? $_REQUEST['pwd1']:null;
$pwd2 = isset($_REQUEST['pwd2']) ? $_REQUEST['pwd2']:null;
$phone = isset($_REQUEST['phone'])? $_REQUEST['phone']:null;
$address = isset($_REQUEST['address'])? $_REQUEST['address']:null;
$name = isset($_REQUEST['name'])? $_REQUEST['name']:null;
$name = trim($name);
$resData = null;
$resData = checkRegisterParams($email,$pwd1,$pwd2);
if(!$resData && checkUserEmail($email)){
$resData['success'] = false;
$resData['message'] = "Пользователь с таким email('{$email}') уже зарегистрирован.";
}
if(!$resData){
$pwdMD5 = md5($pwd1);
$userData = registerNewUser($email,$pwdMD5,$name,$phone,$address);
if($userData['success']){
$resData['message'] = "Пользователь успешно зарегистрирован.";
$resData['success'] = 1;
$userData = $userData[0];
$resData['userName'] = $userData['name'] ? $userData['name']:$userData['email'];
$resData['userEmail'] = $email;
$_SESSION['user'] = $userData;
$_SESSION['user']['displayName'] = $userData['name'] ? $userData['name']:$userData['email'];
}
else{
$resData['success'] = 0;
$resData['message'] = "Ошибка регистрации";
}
}
echo json_encode($resData);
}
?>
<!-- модель для таблицы пользователей -->
<?php
// регистрация нового пользователя
function registerNewUser($email,$pwdMD5,$name,$phone,$address){
global $db;
$email = htmlspecialchars(mysqli_real_escape_string($db,$email));
$name = htmlspecialchars(mysqli_real_escape_string($db,$name));
$phone = htmlspecialchars(mysqli_real_escape_string($db,$phone));
$address = htmlspecialchars(mysqli_real_escape_string($db,$address));
$sql = "INSERT INTO `users`(`email`,`pwd`,`name`,`phone`,`address`) VALUES('{$email}','{$pwdMD5}','{$name}','{$phone}','{$address}')";
$rs = mysqli_query($db,$sql);
if($rs){
$sql = "SELECT * FROM `users` WHERE `email` = '{$email}' AND `pwd` = '{$pwdMD5}' LIMIT 1";
$rs = mysqli_query($db,$sql);
$rs = createSmartyRsArray($rs);
if($rs[0]){
$rs['success'] = 1;
}
else{
$rs['success'] = 0;
}
}
else{
$rs['success'] = 0;
}
return $rs;
}
//проверка параметров для регистрации пользователей
function checkRegisterParams($email,$pwd1,$pwd2){
$res = null;
if(!$email){
$res['success'] = false;
$res['message'] = 'Введите имайл';
}
if(!$pwd1){
$res['success'] = false;
$res['message'] = 'Введите пароль';
}
if(!$pwd2){
$res['success'] = false;
$res['message'] = 'Введите повтор пароля';
}
if($pwd1 != $pwd2){
$res['success'] = false;
$res['message'] = 'Пароли не совпадают';
}
return $res;
}
// проверка почты(есть ли имайл в БД)
function checkUserEmail($email){
global $db;
$email = mysqli_real_escape_string($db,$email);
$sql = "SELECT id FROM `users` WHERE `email` = '{$email}'";
$rs = mysqli_query($db,$sql);
$res = createSmartyRsArray($rs);
return $res;
}
?>
array(4) {
["message"]=>
string(71) "Пользователь успешно зарегистрирован."
["success"]=>
int(1)
["userName"]=>
string(10) "[email protected]"
["userEmail"]=>
string(10) "[email protected]"
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question