我正在尝试创建一个网站并立即编写我正在创建我的登录页面。我成功检查了用户是否存在。但是如果错误,我想返回一个错误,并且只能使用JavaScript。我的PHP文件使用AJAX运行。我尝试了很多解决方案,但没有一个有效。我尝试将脚本标签放在echo中,但这不起作用。所以基本上我想在PHP中运行我的JavaScript代码。
我的HTML代码:
<!DOCTYPE html>
<html>
<head>
<title>NHG</title>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link type="text/css" rel="stylesheet" href="css/normalize.css"/>
<link type="text/css" rel="stylesheet" href="css/style.css"/>
<link type="text/css" rel="stylesheet" href="css/resposive.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="JS/script.js"></script>
<script src="JS/jQuery.js"></script>
</head>
<body>
<div id="abhimanyu">
<p>"Life will test you but remember this, when you walk up a mountain your legs get stronger"</p>
</div>
<div id="arjun">
<p>"There is no such thing as a failed experiment, only experiments with unexpected outcomes"</p>
</div>
<br>
<div id="bheem">
<p>"Do not look where you fell, but where you slipped."</p>
</div>
<div id="eklavya">
<p>"Sometimes life touches one person with a bouquet and another with a thorn bush, but the first may find a wasp in the flowers, and the second may discover roses among the thorns."</p>
</div>
<header>
<div id="main-head">
<!-- REMEMBER TO CHANGE THE COLOR OF HEADING -->
<a href="#" id="main-heading"><h2><span>sKool</span><span>Talk</span></h2></a>
</div>
</header>
<section>
<div id="container">
<div id="wrapper">
<img src="https://i.imgsafe.org/a40bbe047e.png" alt="avatar" id="schoolAvatar" align="middle">
<div id="admissionNumberDiv">
<form method="get" id="admissionNumber">
<input type="text" name="admissionNumber" id="admissionNumberBox" placeholder="Enter your asmission number..."/>
<br>
<input type="password" name="password" id="password" placeholder="Enter your Password...">
<br>
<button type="submit" id="admissionSubmitButton">
<p>Next</p>
</button>
<br>
<p id="loginErrorMessage"></p>
</form>
<br>
</div>
</div>
</div>
</section>
<br>
<footer>
<div class="footerHR">
</div>
</footer>
</body>
</html>
我的JS:
$(document).ready(function() {
$('#schoolSubmitButton').click(function(){
var schoolName = $('#schoolNameBox').val().toLowerCase();
switch (schoolName) {
case 'new horizon gurukul':
$('#container').remove();
$.get("NHGLogin.php", function(data){
var NGHLogin = $(data).find('div#container');
$('body').append(NGHLogin);
});
break;
default:
$('#schoolErrorMessage').text('Please Enter a valid school name, still if invalid schoold does not exist!').css('color', 'red');
}
});
var name = $('#admissionNumberBox').val();
var pwd = $('#password').val();
var dataString = "admissionNumber: " + name;
$('#admissionSubmitButton').click(function() {
$.ajax({
url: 'php/login.php',
method: 'get',
cache: 'true',
dataType: 'html',
data: {'admissionNumber': name, 'password': pwd},
success: function(response){
$('#container').append(response);
$('body').append(response);
$('#loginErrorMessage').text(response);
alert(response);
}
});
});
});
和我的PHP:
<?php
session_start();
$dbserver = "localhost:3306";
$dbuser = "root";
$dbpass = "";
$dbname = "NewHorizonGurukul";
$username = $_GET['admissionNumber'];
$password = $_GET['password'];
// Create connection
$conn = new mysqli($dbserver, $dbuser, $dbpass, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM Users WHERE AdmissionNumber='$username' AND Password='$password';";
$result = $conn->query($sql);
$numRows = $result->num_rows;
$row = $result->fetch_assoc();
if ($numRows > 0) {
header('location: ../random.php');
echo "<script>window.location('../random.php')<script/>";
} else {
echo '<script type="text/javascript">',
'document.getElementById("loginErrorMessage").innerHTML = "Pleas enter a valid username or password";',
'</script>';
}
?>
以下是它的回报:
答案 0 :(得分:1)
使用以下代码更新您的代码。并尝试
//JS Part:
$("#admissionNumber").on('submit',function(e){
e.preventDefault();
$data = $(this).serialize();
$URL = 'php/'+$(this).attr('data-param-uri')+'.php';
_Form.__Link($URL, $data,function (return_data){
if(typeof (return_data.url) !== 'undefined' && return_data.success === true ){
$(document).find("#loginErrorMessage").html("");
window.location.href = return_data.url;
}else{
$(document).find("#loginErrorMessage").html(return_data.msg);
}
});
});
_Form = {
__Link: function ($url, $data, callback){
$.ajax({
url: $url,
data: $data,
type: 'POST',
dataType: 'json',
processData: false,
contentType: 'application/x-www-form-urlencoded',
cache:false,
success: function (data) {
callback(data);
}
});
}
}
});
$("#admissionNumberBox").on('blur',function(e){
$(document).find("#loginErrorMessage").html("");
});
$("#password").on('blur',function(e){
$(document).find("#loginErrorMessage").html("");
});
// PHP Part:
function loginUser($FORMDATA){
global $conn;
if(empty($FORMDATA)){ $RESP['success'] = false;$RESP['msg'] = "NullData";return json_encode($RESP);}
$sql = "SELECT * FROM Users WHERE AdmissionNumber='".$FORMDATA['admissionNumber']."' AND Password='".$FORMDATA['password']."'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
//if only one user is there than is valid
if(($result->num_rows) == 1){
$RESP['success'] = true;
$RESP['msg'] = "Logged in successfully..!!";
$RESP['url'] = 'random.php';
}else{
$RESP['success'] = false;
$RESP['msg'] = "Please check credentials and try again..!!";
}
return json_encode($RESP);// Js Accept Json Responses
}
答案 1 :(得分:0)
您可以发送错误,例如:
header('HTTP/1.1 500 Internal Server Booboo');
header('Content-Type: application/json; charset=UTF-8');
die(json_encode(array('message' => 'ERROR', 'code' => 1337)));
代替你的
echo '<script type="text/javascript">',
'document.getElementById("loginErrorMessage").innerHTML = "Pleas enter a valid username or password";',
'</script>';
然后使用ajax中的error属性捕获错误
$.ajax({
url: 'php/login.php',
method: 'get',
cache: 'true',
dataType: 'html',
data: {'admissionNumber': name, 'password': pwd},
success: function(response){
$('#container').append(response);
$('body').append(response);
alert(response);
}
error : function(){alert('An Error Has Occurred')}
});