i'm traying to login with ajax and php, in that situation i'm logging succesfuly actually. But i'm trying to make an alert and refresh the page when logged in.
When i attempt to login, its gives me error and no refreshing. But if i refresh the page, i see i have session in php. I don't understand why.
Here is my code;
<script>
$(document).ready(function(){
$('#login_btn').click(function(){
var email = $('#email').val();
var password = $('#password').val();
if(email == '' || password == ''){
$("#login_error").html("*** Please enter your email / password");
}else{
$('#login_error').html("<strong class='text-success'>Validating...</strong>");
$.ajax({
url: "login.php",
method: "post",
data:{email:email, password:password},
success: function(data){
if (data === 'yes') {
window.location.reload();
}else{
$('#login_error').html("<strong class='text-danger'>ERROR...</strong>");
}
}
});
}
});
});
</script>
login php:
<?php
session_start();
include ('../config/setup.php'); #database connection
if(isset($_POST['email'])){
$q = "SELECT * FROM users WHERE email = '$_POST[email]' AND password = '$_POST[password]'";
$r = mysqli_query($dbc, $q);
if(mysqli_num_rows($r) > 0){
$_SESSION['email'] = $_POST['email'];
echo "yes";
}else{
echo "no";
}
}
?>
Html: (Using login form inside a modal)
<div class="modal-body">
<div class="form-horizontal">
<div class="form-group">
<label for="email" class="col-sm-4 control-label">Email</label>
<div class="col-sm-8">
<input type="email" class="form-control" name="email" id="email" placeholder="Account Email">
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-4 control-label">Password</label>
<div class="col-sm-8">
<input type="password" class="form-control" name="password" id="password" placeholder="Account Password" >
</div>
</div>
<div class="form-group">
<div class="col-sm-1"></div>
<div align="center" class="col-sm-10">
<button name="login_btn" id="login_btn" class="btn btn-success btn-block text-center"><span id="loader_before" class="glyphicon glyphicon-log-in" aria-hidden="true"></span><i id="loader" class="fa fa-spinner fa-spin fa-x fa-fw"></i> Log in to Account</button>
</div>
<div class="col-sm-1"></div>
</div>
</div>
<div align="center" class="container-fluid">
<h6><strong class="text-danger">Forgot your password? Click here..</strong></h6>
</div>
<h5><div id="login_error" class="text-warning"></div></h5>
</div>
You just need to update your if block in response as below
`
if (data === 'yes') {
alert("You message here!");
window.location.reload();
}else{
$('#login_error').html("<strong class='text-danger'>ERROR...</strong>");
}
`
When you call echo on php, it will write the value, but not return it. That's the problem.
You are not returning "yes" or "no" from login.php, you're just doing echo, which will only write the value but not return it to the caller.
The ajax call is waiting for a response to process it with the 'success' callback. Since login.php is not returning anything, it will always fall into the else clause.
The solution is to change this on login.php
if(mysqli_num_rows($r) > 0){
$_SESSION['email'] = $_POST['email'];
return "yes";
}else{
return "no";
}
Related
I'm trying to make a new look for my website, but it looks like it doesn't want to login and I don't understand why.. Here's the original page:
<body class="jumbotron vertical-center" onload="redirect();">
<div class="container login-container">
<div class="row">
<div class="col-md-4 login-form mx-auto">
<h3>Login</h3>
<h6>Don't have an account? Register</h6>
<form>
<div class="error-message" id="errorMessage"></div>
<div class="form-group">
<input id="enterID" type="text" class="form-control" placeholder="Your User ID *" value="" required/>
</div>
<div class="form-group">
<input id="password" type="password" class="form-control" placeholder="Your Password *" value="" required/>
</div>
<div class="form-group">
<input class="btn btn-block btn-primary" value="Login" onclick="login();" readonly />
</div>
<div class="form-group">
Trouble logging in?
</div>
</form>
</div>
</div>
</div>
</body>
And here's the edited page:
<!-- To keep it in the center of page-->
<img class="wave" src="img/wave.png">
<div class="container_main">
<div class="img">
<img src="img/bg.svg">
</div>
<div class="login-content">
<form>
<img src="img/avatar.svg">
<h2 class="title">Quiz Website</h2>
<div class="input-div one">
<div class="i">
<i class="fas fa-user"></i>
</div>
<div class="div">
<input type="text" class="input" id="enterID" placeholder="Username">
</div>
</div>
<div class="input-div pass">
<div class="i">
<i class="fas fa-lock"></i>
</div>
<div class="div form-group">
<input id="password" type="password" class="form-control" placeholder="Password" value="" required/>
</div>
</div>
Don't have an account?
<div class="form-group">
Trouble logging in?
</div>
<input type="submit" class="btn" value="Login" onclick="login();" readonly >
<div class="error-message" id="errorMessage"></div>
</form>
</div>
</div>
</html>
What am I doing wrong? I don't want to use the body class jumbotron vertical-center cause it's making my website to look very awful.. I always get ,,XHR loading failed" and I don't understand why..
My checklogin.js file:
function login() {
var enterID = document.getElementById("enterID").value;
var password = document.getElementById("password").value;
if ((password != "") && (enterID != "")) {
var info = "?enterID=" + enterID + "&password=" + password;
$.ajax
({
type: "GET",
url: "php/login.php" + info,
success: function (respond) {
if (respond == "admin") {
window.location.href = "page/admin-system-management.php";
} else if (respond == "student") {
window.location.href = "page/student-dashboard.php";
} else if (respond == "teacher") {
window.location.href = "page/teacher-dashboard.php";
} else {
document.getElementById("errorMessage").innerText = respond;
}
}
});
}
else {
document.getElementById("errorMessage").innerText = "Please fill in all the fields.";
}
}
function redirect() {
$.ajax
({
type: "GET",
url: "php/redirect.php",
success: function (respond) {
if (respond != "not logged.") {
if (respond == "admin") {
window.location.href = "page/admin-system-management.php";
} else if (respond == "student") {
window.location.href = "page/student-dashboard.php";
} else if (respond == "teacher") {
window.location.href = "page/teacher-dashboard.php";
}
}
}
});
}
And my login.php file:
<?php
include "mysql-connect.php";
//get Info from login.html
$ID = $_GET['enterID'];
$PW = $_GET['password'];
$stmt = $connect->prepare("SELECT PW, userType, nickName FROM users WHERE ID = ?");
$stmt->bind_param("s",$ID);
$valid = $stmt->execute();
if (!$valid){
die("Could not successfully run query.". $connect->connect_error);
}
$result = $stmt->get_result();
if ($result->num_rows==0){
//display message of no such student/teacher/admin
echo "Failed to find an account with the input ID.";
} else {
$row = $result->fetch_assoc();
if (password_verify($PW, $row['PW'])) {
$type = $row['userType'];
$nick = $row['nickName'];
//var_dump($row['PW']);
//save data
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
$_SESSION["type"]=$type;
$_SESSION["userID"]=$ID;
$_SESSION["nickName"]=$nick;
//login success - Request.responseText to checklogin.js
echo $type;
} else {
//display message of password error
echo "The input password does not match the account password.";
}
}
$connect->close();
?>
And here's the redirect.php:
<?php
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if (isset($_SESSION["type"])){
if ($_SESSION["type"] != $_SESSION["pageType"]){
$alert_message = "You cannot access this page using your account!";
$link = "../login.html";
echo "<script type='text/javascript'>alert('$alert_message'); window.setTimeout(function(){ if ('".$_SESSION["type"]."'=='admin'){ window.location.href = '../page/admin-system-management.php';} else if ('".$_SESSION["type"]."'=='student'){ window.location.href = '../page/student-dashboard.php';} else if ('".$_SESSION["type"]."'=='teacher'){ window.location.href = '../page/teacher-dashboard.php';} }, 0);</script>";
}
} else {
$alert_message = "Your login period has expired! Please login again!";
$link = "../login.html";
echo "<script type='text/javascript'>alert('$alert_message'); window.setTimeout(function(){ window.location.href = '$link'; }, 0);</script>";
}
?>
I'm trying to log in and then redirect to a custom page, based on user type. My problem is that when I'm pressing the login button, on the console I get that that I have a Undefined array key pageType, and I don't understand why... If I'm for example on teacher page, I set $_SESSION['pageType'] = 'teacher';
This my login.html page:
<img class="wave" src="img/wave.png">
<div class="container_main" onsubmit="redirect();">
<div class="img">
<img src="img/bg.svg">
</div>
<div class="login-content">
<form onsubmit="redirect();">
<img src="img/avatar.svg">
<h2 class="title">Quiz Website</h2>
<div class="input-div one">
<div class="i">
<i class="fas fa-user"></i>
</div>
<div class="div">
<input type="text" class="input" id="enterID" placeholder="Username">
</div>
</div>
<div class="input-div pass">
<div class="i">
<i class="fas fa-lock"></i>
</div>
<div class="div form-group">
<input id="password" type="password" class="form-control" placeholder="Password" value="" required/>
</div>
</div>
Don't have an account?
<div class="form-group">
Trouble logging in?
</div>
<input type="submit" class="btn" value="Login" onclick="login();" readonly >
<div class="error-message" id="errorMessage"></div>
</form>
</div>
</div>
</html>
This is checklogin.js:
function login() {
var enterID = document.getElementById("enterID").value;
var password = document.getElementById("password").value;
if ((password != "") && (enterID != "")) {
var info = "?enterID=" + enterID + "&password=" + password;
$.ajax
({
type: "GET",
async: true,
url: "php/login.php" + info,
success: function (respond) {
if (respond == "admin") {
window.location.href = "page/admin-system-management.php";
} else if (respond == "student") {
window.location.href = "page/student-dashboard.php";
} else if (respond == "teacher") {
window.location.href = "page/teacher-dashboard.php";
} else {
document.getElementById("errorMessage").innerText = respond;
}
}
});
}
else {
document.getElementById("errorMessage").innerText = "Please fill in all the fields.";
}
}
function redirect() {
$.ajax
({
type: "GET",
async: true,
url: "php/redirect.php",
success: function (respond) {
if (respond != "not logged.") {
if (respond == "admin") {
window.location.href = "page/admin-system-management.php";
} else if (respond == "student") {
window.location.href = "page/student-dashboard.php";
} else if (respond == "teacher") {
window.location.href = "page/teacher-dashboard.php";
}
}
console.log(respond)
}
});
}
And this is my redirect.php file:
<?php
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if (isset($_SESSION["type"])){
if ($_SESSION["type"] != $_SESSION["pageType"]){
$alert_message = "You cannot access this page using your account!";
$link = "../login.html";
echo "<script type='text/javascript'>alert('$alert_message'); window.setTimeout(function(){ if ('".$_SESSION["type"]."'=='admin'){ window.location.href = '../page/admin-system-management.php';} else if ('".$_SESSION["type"]."'=='student'){ window.location.href = '../page/student-dashboard.php';} else if ('".$_SESSION["type"]."'=='teacher'){ window.location.href = '../page/teacher-dashboard.php';} }, 0);</script>";
}
} else {
$alert_message = "Your login period has expired! Please login again!";
$link = "../login.html";
echo "<script type='text/javascript'>alert('$alert_message'); window.setTimeout(function(){ window.location.href = '$link'; }, 0);</script>";
}
?>
What I suspect is that the redirect() function it's not even loaded, so that's why I think I'm getting this error... Sometimes I'm seeing ,,XHR failed loading: GET"
I modified a code in order to have another login.html page, this is my old login.html code:
<body class="jumbotron vertical-center" onload="redirect();">
<div class="container login-container">
<div class="row">
<div class="col-md-4 login-form mx-auto">
<h3>Login</h3>
<h6>Don't have an account? Register</h6>
<form>
<div class="error-message" id="errorMessage"></div>
<div class="form-group">
<input id="enterID" type="text" class="form-control" placeholder="Your User ID *" value="" required/>
</div>
<div class="form-group">
<input id="password" type="password" class="form-control" placeholder="Your Password *" value="" required/>
</div>
<div class="form-group">
<input class="btn btn-block btn-primary" value="Login" onclick="login();" readonly />
</div>
<div class="form-group">
Trouble logging in?
</div>
</form>
</div>
</div>
</div>
</body>
Inside redirect() function add this line at the start.
This will stop the forms default action of redirecting/refreshing the page
event.preventDefault();
Then your redirect function / respond variable should work
If you return this from php it will be ignored by javascript
echo "<script type='text/javascript'>code here\</script>";
To make your redirect.php easier to debug output the data as a json encoded array instead of a string that way you can view/test more data.
inside redirect.php try add this code straight after the session_start() line just as a first test
$data = [
'session' => $_SESSION,
'response' => 'place your response here',
];
echo json_encode($data);
exit;
Ok here is the update i think you need.
redirect.php
<?php
if(!session_id()) {
session_start();
}
// you can change this line to this once you have debugged your code - $data = [];
$data = ['session' => $_SESSION];
// place code here to get the user type from the database
// then use $_SESSION['type'] = '{database response}';
if(!isset($_SESSION['type']))
{
$_SESSION['type'] = null;
}
switch($_SESSION['type']) {
case 'admin':
header('Location: /page/admin-system-management.php'); // this is the php way to redirect
break;
case 'student':
header('Location: /page/student-dashboard.php');
break;
case 'teacher':
header('Location: /page/teacher-dashboard.php');
break;
default:
$data['alert_message'] = 'Your login period has expired! Please login again!';
}
echo json_encode($data);
exit;
?>
Javascript redirect function
function redirect() {
$.ajax
({
type: "GET",
async: true,
url: "php/redirect.php",
success: function (response) {
console.log(response);
if(response.alert_message) {
alert(response.alert_message);
}
}
});
}
i am trying do validate my form data on frontend and backend also using jquery and php using post method on jquery.
<form>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
this is my form how can i validate it on frontend and also backend without page refresh
<script>
$(document).ready(function(){
$("button").on("click", function(){
let email = $.trim($("#exampleInputEmail1").val());
let password = $.trim($("#exampleInputPassword1").val());
if(email === ""){
alert("Email is required!");
return false;
}
if(password === ""){
alert("Password is required!");
return false;
}
$.post("login.php",{email : email , password : password}, function(response){
response = JSON.parse(response);
if(response.success){
// redirect to homepage
}else{
alert(response.message);
}
});
});
});
</script>
login.php
<?php
$email = $_POST["email"];
$password = $_POST["password"];
if($email === ""){
echo json_encode(array("success" => false,"message" => "Email is required!"));
exit;
}
if($password === ""){
echo json_encode(array("success" => false,"message" => "Password is required!")); exit;
}
//check the record in db and send back the response
?>
I ve been searching all relative questions here and still cant figure out the problem I have.
I am using a simple modal form :
<p id="messages">Let's make today a great day!</p>
<form id="myloginform" name="myloginform" action="scripts/login.php" method="post" >
<div class="form-group">
<label for="username" class="">Enter username</label>
<input type="text" class="form-control input-lg c-square" id="username" name="username" placeholder="Username" required> </div>
<div class="form-group">
<label for="password" class="">Enter pass</label>
<input type="password" class="form-control input-lg c-square" id="password" name="password" placeholder="Password" required> </div>
<div class="form-group">
<div class="c-checkbox">
<input type="checkbox" id="login-rememberme" class="c-check">
<label for="login-rememberme" class="c-font-thin c-font-17">
<span></span>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn c-theme-btn btn-md c-btn-uppercase c-btn-bold c-btn-square c-btn-login" id="check">login</button>
</div>
</form>
I am using ajax to pass the form to a php file :
<script>
$(document).ready(function(){
$('form#myloginform').submit(function(e) {
var my_data = $('form#myloginform').serialize();
$.ajax({
type : 'POST',
url : 'scripts/login.php',
cache : false,
data : my_data,
contentType : false,
processData : false,
dataType: 'json',
success: function(response) {
//TARGET THE MESSAGES DIV IN THE MODAL
if(response.type == 'success') {
$('#messages').addClass('alert alert-success').text(response.message);
} else {
$('#messages').addClass('alert alert-danger').text(response.message);
}
}
});
e.preventDefault();
});
});
</script>
The login.php file is very simple and returns an json $output response
<?php
$username = $_POST['username'];
$password = $_POST['password'];
if($username == "Test"){
$success = true;
}
if($success == true) {
$output = json_encode(array('type'=>'success', 'message' => $username));
} else {
$output = json_encode(array('type'=>'error', 'message' => $username));
}
die($output);
?>
The $output in every case returns null. I checked with firebug, and everything is OK , no errors, POST perfect still I cannot get the variables in php to work. Any ideas ??? Is something wrong with my approach or do I need to deserialize the data in the php file , somehow...???
Don't use die.
Use echo or print.
Also set contentType to true.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I need help to find what mistake I am doing , because I'm trying to develop a function that send email from a HTML form using php and ajax , the problem I'm facing is whenever I click on submit bouton the page is refreshing , usually as we can see in the javascript script , I'm supposed to receive a message that shows that it was successfully send
Best regards,
PHP File :
<?php
if (isset($_REQUEST['email'])) {
//Email information
$admin_email = "basselbizri#gmail.com";
$name = $_REQUEST['first_name'];
$email = $_REQUEST['email'];
$message = $_REQUEST['message'];
//send email
if (mail($admin_email, $name, $message, "From:" . $email)) {
echo 1;
}
else {
echo 0;
}
}
?>
HTML Form :
<form class="inline" id="contactForm" method="post" >
<div class="row">
<div class="col-sm-6 height-contact-element">
<div class="form-group">
<input type="text" name="first_name" class="form-control custom-labels" id="name" placeholder="FULL NAME" required data-validation-required-message="Please write your name!"/>
<p class="help-block text-danger"></p>
</div>
</div>
<div class="col-sm-6 height-contact-element">
<div class="form-group">
<input type="email" name="email" class="form-control custom-labels" id="email" placeholder="EMAIL" required data-validation-required-message="Please write your email!"/>
<p class="help-block text-danger"></p>
</div>
</div>
<div class="col-sm-12 height-contact-element">
<div class="form-group">
<input type="text" name="message" class="form-control custom-labels" id="message" placeholder="WHAT'S ON YOUR MIND" required data-validation-required-message="Please write a message!"/>
</div>
</div>
<div class="col-sm-3 col-xs-6 height-contact-element">
<div class="form-group">
<input type="submit" class="btn btn-md btn-custom btn-noborder-radius" value="Send It"/>
</div>
</div>
<div class="col-sm-3 col-xs-6 height-contact-element">
<div class="form-group">
<button type="button" class="btn btn-md btn-noborder-radius btn-custom" name="reset">RESET
</button>
</div>
</div>
<div class="col-sm-3 col-xs-6 height-contact-element">
<div class="form-group">
<div id="response_holder"></div>
</div>
</div>
<div class="col-sm-12 contact-msg">
<div id="success"></div>
</div>
</div>
</form>
JS Script :
$('#contactForm').on('submit', function(e){
e.preventDefault();
e.stopPropagation();
// get values from FORM
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
var goodToGo = false;
var messgaeError = 'Request can not be send';
var pattern = new RegExp(/^(('[\w-\s]+')|([\w-]+(?:\.[\w-]+)*)|('[\w-\s]+')([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
if (name && name.length > 0 && $.trim(name) !='' && message && message.length > 0 && $.trim(message) !='' && email && email.length > 0 && $.trim(email) !='') {
if (pattern.test(email)) {
goodToGo = true;
} else {
messgaeError = 'Please check your email address';
goodToGo = false;
}
} else {
messgaeError = 'You must fill all the form fields to proceed!';
goodToGo = false;
}
if (goodToGo) {
$.ajax({
data: $('#contactForm').serialize(),
beforeSend: function() {
$('#success').html('<div class="col-md-12 text-center"><img src="images/spinner1.gif" alt="spinner" /></div>');
},
success:function(response){
if (response==1) {
$('#success').html('<div class="col-md-12 text-center">Your email was sent successfully</div>');
window.location.reload();
} else {
$('#success').html('<div class="col-md-12 text-center">E-mail was not sent. Please try again!</div>');
}
},
error:function(e){
$('#success').html('<div class="col-md-12 text-center">We could not fetch the data from the server. Please try again!</div>');
},
complete: function(done){
console.log('Finished');
},
type: 'POST',
url: 'js/send_email.php',
});
return true;
} else {
$('#success').html('<div class="col-md-12 text-center">'+messgaeError+'</div>');
return false;
}
return false;
});
});
In your success() method you're reload()'ing the page.
if (response==1) {
$('#success').html('<div class="col-md-12 text-center">Your email was sent successfully</div>');
window.location.reload(); // <----- remove this; it's causing the page to reload
}
So when your mail() function resolves true, in your PHP file (send_email.php), you're returning 1 to your AJAX response which is allowing the if (response == 1) to satisfy, and then you're using window.location.reload() to reload the page. Removing window.location.reload(); will keep the page from reloading.