我正在尝试使用Ajax从html表单发送输入,并尝试在MySQL数据库中优化电子邮件。我测试了搜索,并且工作正常(使用伪数据。)我的PHP文件在WAMP上运行。我检查了Chrome,以查看是否显示了电子邮件/密码。 这是我的代码:
HTML和Ajax
<html>
<head>
<!--initialize jquery from js folder-->
<script src ="js/jquery-3.3.1.min.js"></script>
</head>
<body>
<!--output of the json-->
<div>
<!--set the id to DOM to show output-->
<ul id="DOM">
</ul>
</div>
<form>
<label><b>Email</b></label>
<input type="text" placeholder="Enter email" id="email"
required>
<br/>
<label><b>Password</b></label>
<input type="text" placeholder="Enter password" id="passwrd"
required>
<br/>
<button type="button" id="submit">Login</button>
</form>
<a href="insert.html">insert</a>
<a href="delete.html">delete</a>
<a href="index.html">show data</a>
<a href="login.html">login</a>
<!--Implementation of jquery/ajax-->
<script type="text/javascript">
$('#submit').on('click',function(e){
e.preventDefault()
var data = {
email: $("#email").val(),
passwrd: $("#passwrd").val()
}
$.ajax({
url : "http://localhost/api/login.php",
type : "POST",
dataType : "json",
data : JSON.stringify(data),
//on success it will call this function
success : function(data){
alert(data.toString());
//if fail it will give this error
}, error : function(e){
alert("failed to work:" +JSON.stringify(e));
}
});
});
</script>
</body>
</html>
PHP
include "db.php";
header('Content-type: application/json');
//$con->escape_string
$email = isset($_POST['email']);
//$email = "fk5829@wayne.edu";
$result = $con->query("SELECT * FROM users WHERE email='$email'");
echo "$email";
if($result->num_rows == 0){ //if the user doesnt exist
$_SESSION['message'] = "user doesnt exist";
echo ' / user not exist / ';
}
else{ //user exists
$user = $result->fetch_assoc();
if(password_verify(isset($_POST['passwrd']), $user['passwrd'])){
//Verify the password entered
//if password correct, link information from DB to session
//variables
$_SESSION['f_name']= $user['f_name'];
$_SESSION['l_name']= $user['l_name'];
$_SESSION['email']= $user['email'];
$_SESSION['authorized']= $user['authorized'];
//Will be used to check if users session is logged
//in/allowed to do things
$_SESSION['logged_in'] = true;
//return to Success
return $_SESSION['logged_in'];
exit("Success");
}
else{
$_SESSION['message'] = "You have entered the wrong password,
please try again";
}
echo ' / user exists / ';
}
echo ' / After the check / ';
我的问题是:为什么表单ID为“ email”的电子邮件没有存储在$ email中?在我的ajax请求方面吗?还是我尝试$ _POST时在我的PHP文件中?
任何方向都值得赞赏。
答案 0 :(得分:0)
我尝试了此功能并使它起作用。也许您也可以尝试一下。
<script type="text/javascript">
$('#submit').on('click',function(e){
e.preventDefault()
$.post('http://localhost/api/login.php', {email:$("#email").val(),passwrd:$("#passwrd").val()},
function(data){
alert(data.toString());
}).fail(function(e){
alert("failed to work:" +JSON.stringify(e));
});
});
</script>