此JavaScript代码使用POST方法将数据从表单发送到PHP,如果数据为true,则PHP检查数据库。但是我不知道如何将PHP的响应发送给JS,提取成功。有人可以解释一下吗?
JS:
$('#submit-btn').on('click', function() {
var dataString = 'username=' + document.getElementById('username').value + '&password=' + document.getElementById('password').value + '&rememberMe=' + document.getElementById('rememberMe').value;
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: dataString,
cache: false,
success: function(){
//check if what response is
}
});
ajaxsubmit.php:
<?php
session_start();
//connect
$username =$_POST['username'];
$password =$_POST['password'];
$sql = "SELECT * FROM user WHERE email ='$username' OR username ='$username' AND password = '$password'";
$result = mysqli_query($conn, $sql);
if(!$row = mysqli_fetch_assoc($result)){
//response error
} else{
//response success
}
?>
答案 0 :(得分:1)
你必须在PHP中回应一些东西才能得到回报:
if(!$row = mysqli_fetch_assoc($result)){
//response error
echo 'there is a problem';
} else {
//response success
echo 'yippee!';
}
然后您可以按如下方式记录退货:
$('#submit-btn').on('click', function() {
var dataString = 'username=' + document.getElementById('username').value + '&password=' + document.getElementById('password').value + '&rememberMe=' + document.getElementById('rememberMe').value;
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: dataString,
cache: false,
success: function(data){ // 'data' is the variable holding the return from PHP's echo
//check if what response is
console.log(data);
}
});
警告 Little Bobby说 your script is at risk for SQL Injection Attacks. 了解prepared MySQLi语句。即使escaping the string也不安全!
危险 从不存储纯文本密码!请使用 PHP的built-in functions 来处理密码安全问题。如果您使用的PHP版本低于5.5,则可以使用password_hash()
compatibility pack。 没有必要escape passwords 或在散列之前对它们使用任何其他清理机制。这样做更改密码并导致不必要的额外编码。
答案 1 :(得分:0)
无论你在php中回应什么,都会被发送回ajax。
if(!$row = mysqli_fetch_assoc($result)){
echo 0;
}
else{
echo 1;
}
success: function(response){
//check if what response is
console.log( response );
}
答案 2 :(得分:0)
您可以退出带有响应参数的方法。喜欢:
ajaxsubmit.php
if(!$row = mysqli_fetch_assoc($result)){
exit('error'); //exit with response 'error'
} else{
exit('success'); //exit with response 'success'
}
JS
$('#submit-btn').on('click', function() {
var dataString = 'username=' + document.getElementById('username').value + '&password=' + document.getElementById('password').value + '&rememberMe=' + document.getElementById('rememberMe').value;
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: dataString,
cache: false,
success: function(response){
//check if what response is
console.log(response);
}
});