所以当我点击我的注册页面上的一个按钮(register.php)时,jQuery应该向regit.php发出一个AJAX发布请求。在jQuery中我添加了一个调试消息(它确实注册了按钮单击),但之后没有任何反应。没有数据返回结果div,没有。
我试图找到错误但却无法发现它。
使用Javascript:
$(function(){
$("form").submit(function() {
event.preventDefault();
console.log("clicked button");
var username = $('#username').val();
var password = $('#password').val();
var passwordconfirm = $('#password_confirm').val();
var email = $('#email').val();
var turvakysimus = $('#turvakysimus').val();
var turvavastus = $('#turvavastus').val();
$.post("regit.php",
{
username: username,
password: password,
passwordconfirm: passwordconfirm,
email: email,
turvakysimus: turvakysimus,
turvavastus: turvavastus
},
function(data)
{
if(data.tulemus == 'olemas') {
$("#resultDiv").hide().html('<div class="alert alert-success" style="margin-top:25px;"> <strong>Success!</strong></div>').fadeIn(1000);
} else if (data.tulemus == 'loodud'){
$("#resultDiv").hide().html('<div class="alert alert-danger" style="margin-top:25px;"> <strong>Error!</strong></div>').fadeIn(1000);
}
}, "json");
});
});
将请求发送到的regit.php:
<?php
if(isset($_POST['username'])){
include_once 'db_connect.php';
$username = $_POST['username'];
$password = $_POST['password'];
$passwordconfirm = $_POST['passwordconfirm'];
$email = $_POST['email'];
$turvakysimus = $_POST['turvakysimus'];
$turvavastus = $_POST['turvavastus'];
$sql = "SELECT username FROM kasutajad WHERE username = :username";
$query = $pdo->prepare($sql);
$query->bindValue(':username', $username);
$query->execute();
$query->fetch(PDO::FETCH_ASSOC);
if($query->rowCount()){
echo json_encode(array("tulemus"=>"olemas"));
} else {
$passwordHash = password_hash($password, PASSWORD_DEFAULT);
$sql = "INSERT INTO users (username, password, email, turvakysimus, turvavastus) VALUES (:username, :password, :email, :turvakysimus, :turvavastus)";
$query = $pdo->prepare($sql);
$query->bindValue(':username', $username);
$query->bindValue(':password', $passwordHash);
$query->bindValue(':email', $email);
$query->bindValue(':turvakysimus', $turvakysimus);
$query->bindValue(':turvavastus', $turvavastus);
$result = $query->execute();
if($result){
echo json_encode(array("tulemus"=>"loodud"));
}
}
}
?>
任何帮助都会受到赞赏。我只是希望它不是某个愚蠢的错字。
答案 0 :(得分:0)
查看 jQuery.post() 并尝试添加fail
功能,以便在出现任何问题时进行处理:
$.post("regit.php",
{
username: username,
password: password,
passwordconfirm: passwordconfirm,
email: email,
turvakysimus: turvakysimus,
turvavastus: turvavastus
}, function(result) {
alert( "success" );
console.log(result);
}).fail(function() {
alert( "error" );
});
希望这有帮助。