[英]passing login data from ajax to php script
這是我在html頁面中的腳本:
<script>
$(document).ready(function(){
$('#form').on('submit',function(e){
var loginid=$('#loginid').val();
var password=$('#password').val();
alert("loginid="+loginid);
$.ajax({
type: "POST",
url: "../controller/login_check.php",
data: {loginid:loginid,password:password},
success: function(html) {
//alert(html);
$('#status').html(html);
}
});
});
});
</script>
我試圖從html輸入框中獲取值,然后將這些值傳遞給ajax代碼,然后將其傳遞給php腳本,然后該腳本將驗證登錄ID和密碼並回顯消息
php腳本:
<?php
require_once('dbconfig.php');
//if (isset($_POST['signin'])) {
$loginid = $_POST['loginid'];
$password = $_POST['password'];
if ($operations->login($loginid, $password)) {
header("Location:../view/admin_home.php");
} else {
echo "wrong details";
}
//}
$conn = null;
?>
html div應該在哪里打印消息:
<div id="status"></div>
當我在瀏覽器中運行代碼時,未顯示任何錯誤,但代碼不起作用,也未顯示消息,也未完成驗證。
試試看:
<script>
$(document).ready(function(){
$('#form').on('submit',function(e){
e.preventDefault();
var form = $(this);
$.ajax({
type: form.attr('method'),
url: "../controller/login_check.php",
data: form.serialize()
}).done(function (html) {
$('#status').html(html);
});
});
});
</script>
我通過阻止它執行默認功能來解決了它
我使用了e.preventDefault(),但是我遇到了一個新問題,即php腳本試圖重定向到的頁面出現在同一登錄頁面上,我現在應該如何解決呢? 這是相同的屏幕截圖
您必須使用javascript進行重定向,您實際上並沒有進入php頁面,您只是在檢索打印的內容。
window.open(page,'_self')
而不是
header(...)
我的貢獻:
在ajax請求中,我建議您結束php腳本,可以使用簡單的die();。 為了這。 此后,您必須打印響應,可以使用數字或字符串模式來顯示以下內容:“成功”或“失敗”,也可以是:1或0。
這是帶有新解決方案的相同示例:
<script>
$(document).ready(function(){
$('#form').on('submit',function(e){
var loginid = $('#loginid').val();
var password = $('#password').val();
e.preventDefault(); //for avoiding conflict with default form function
$.ajax({
type: "POST",
url: "../controller/login_check.php",
data: {loginid: loginid, password: password},
success: function(response) {
if (response == 'success') {
// if a successful response, redirect your client
window.location.href = '../view/admin_home.php';
} else {
// if login fails, put a message on screen
$('#status').html('Wrong credentials, try again.');
}
}
});
});
});
</script>
不要忘記在php中過濾數據,永遠不要信任您的用戶!
require_once('dbconfig.php');
// pre setting a response status as fail, this avoid you to use an
// else statement
$result = 'fail';
if (isset($_POST['signin'])) {
// Apply filter and sanitize data, if the loginid is an e-mail
// use the FILTER_SANITIZE_EMAIL else a simple string filter is ok.
$loginid = filter_input(INPUT_POST, 'loginid', FILTER_SANITIZE_EMAIL);
$password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);
if($operations->login($loginid,$password)){
// If everything is ok, you just override the response message
$result = 'success';
}
}
// Ath the end you simply close the connection, print the response and
// stops the PHP script
$conn = null;
print(result);
die();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.