I have a login form in boostrap's modal window
<form method="post" id="loginForm" action="index.php">
<label for="email">Email:</label>
<input class="form-control" type="text" name="email" value="" id="emailLogin"/><br/>
<label for="password">Password:</label>
<input class="form-control" type="password" name="password" value="" id="passwordLogin"/><br/>
<div id="loginAlert" class="alert alert-danger" role="alert">Email or password incorrect</div> <!-- Hidden by default -->
<button type="submit" name="login" class="btn btn-primary" id="loginButton">Login</button>
<script src="checkLoginForm.js"></script></form>
I would like to check this form (if email and password are correct) before submitting it. If the function, which checks the email and password returns 1, there is something incorrect. Form should not submit in this case and it should just make the alert visible.
If everything is correct, it should submit.
Thing is: I can prevent the form from submitting, if the the email and password are incorrect, but I can't submit it, if they are correct. Here is the code from checkLoginForm.js
$(document).ready(function() {
$("#loginForm").submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'include/ajax.php?action=checkLogin',
data: {
email: $("#emailLogin").val(),
password: $("#passwordLogin").val(),
},
success: function(result) {
console.log(result);
if(result == 0) {
} else {
$("#loginAlert").css({"display": "block"});
}
}
});
});
});
I have no idea what to do, when the result == 0. If I do $("loginForm").submit();, that does not submit the form (else part does work).
Thank you for your replies.
I would advice you to use a simple $.post, it's a shorthand way of using $.ajax for POST requests. Just check if the values provided are correct in your php file, if they are correct process that data and return true or redirect the user to another page else return false.
$(document).ready(function() {
$("#loginButton").on('click', function (e){
e.preventDefault();
var email = $("#emailLogin").val();
var passwd = $("#passwordLogin").val();
$.post('include/ajax.php?action=checkLogin', {email: email, password: passwd}, function (data) {
var res = $.parseJSON(data);
if (res.result == true) {
//you can redirect the or display a message to the user.
//redirect the user to another page
//$("#loginAlert").css({"display": "block"}).html("login successful");
}else {
$("#loginAlert").css({"display": "block"});
}
});
});
});
Then in your php file
if (isset($_GET['action']) && $_GET['action'] == 'checkLogin') {
$passwd = trim(filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING));
$email = trim(filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL));
//validate inputs here
//get data from db
//then compare values
//if values match return true
//$db_mail and $db_passwd are from the db.
if ($email == $db_mail && $passwd == $db_passwd) {
//if the provided information is correct
//process it here, login the user.
//redirect if necessary.
// or return results to JS
echo json_encode(['result' => true]);
} else {
//if the information is wrong return false to JS
//and alert the user
echo json_encode(['result' => false]);
}
}
Related
I am trying to create on-page login.
without ajax it works very well. Here is my login.php;
if($_POST)
{
$username =$_POST["username"];
$password =$_POST["password"];
$query = $handler->query("SELECT * FROM members WHERE username='$username' && password='$password'",PDO::FETCH_ASSOC);
if ( $say = $query -> rowCount() ){
if( $say > 0 ){
session_start();
$_SESSION['session']=true;
$_SESSION['username']=$username;
$_SESSION['password']=$password;
echo "ok";
}else{
echo "Couldn't login.";
}
}else{
echo "Wrong username or password.";
}
}
Anyway, here is my java script code;
$(function(){
$("#loginbutton").click(function(){
var username = $("#username").val();
var password = $("#password").val();
if(username != "" && password != ""){
$.ajax("login.php",{
type : "POST",
data : "username="+username+"&password="+password,
success : function(data){
if(data == "ok"){
$("#message").html(data);
}else{
$("#fail").fadeIn();
}
}
});
}
});
});
Even though I put correct login information (when I get "ok" response from login.php, it always outputs $("#fail").fadeIn(); . instead of $("#message").html(data); I couldn't figure out where I am mistaken.
and here is login form:
<div id="login">
<form action="" onsubmit="return false;" method="post">
<input type="text" class="form-control" id="username" name="username" placeholder="Username" autocomplete="off"><br>
<input type="password" class="form-control" id="password" name="password" placeholder="Password" autocomplete="off"><br>
<input class="btn btn-success" type="submit" id="loginbutton" value="Login">
</form>
<div id="message"> </div>
<div id="fail" style="display: none;">failed.</div>
</div>
You are using type as post, but sending parameters as get.Change your ajax like this,
$.ajax("login.php",{
type : "POST",
data : {username:username,password:password},// only this line is changed.
success : function(data){
if(data == "ok"){
$("#message").html(data);
}else{
$("#fail").fadeIn();
}
}
});
Here is a quick example of using post with JQuery AJAX.
$(document).ready(function(){
$.post("login.php", {username:username, password:password}, function(data){
if(data == 'ok'){
$("#message").html(data);
}else{
alert(data);//alert the data you receive. It alerts you if there is any error in php file.
$("#fail").fadeIn();
}
});
});
Hope that was helpful!
Firstly, debug your code like this:
1) On button click you will put alert function inside javascript code. if it is working then move second step.
2) use alert function to print username and password if it comes inside your javascript code and correct as you put into input fields then move third step.
3) use serialize method in javascript.
I hope its help you to get your solution.
Trying to create a login form using AJAX so the page does not have to change to log a user in. So far I have the following after using a tutorial I found however I have the problem of the form is reloading the page instead of calling the JavaScript function.
HTML:
<form class="login-form" onSubmit="check_login();return false;">
<input type="text" name="email" placeholder="Email">
<input type="password" name="password" placeholder="Password">
<button type="submit" class="btn trans login-button">Login</button>
</form>
PHP:
// Retrieve login values from POST variables
$email = strip_tags($_POST['email']);
$password = strip_tags($_POST['password']);
// Salt and hash password for database comparison
$password = saltHash($password);
// Check that both fields are not empty
if(!empty($email) || !empty($password)) {
// Query database to check email and password match entry
$database->query('SELECT * FROM users WHERE email = :email AND password = :password');
$database->bind(':email',$email);
$database->bind(':password',$password);
$result = $database->single();
if(!empty($result)) {
// Check entered details match the database
if($email == $result['email'] && $password == $result['password']) {
// If login details are correct, return 1
echo '1';
}
}
else {
// If not returned results, return 2
echo '2';
}
}
else {
// If either fields are empty, return 3
echo '3';
}
JavaScript / jQuery:
// Login function
function check_login() {
$.ajax({
type: 'POST',
url: 'check-login.php',
data: 'email=' + $('input[value="email"]').val() + '&password=' + $('input[value="password"]').val(),
success: function(response){
if(response === '1') {
alert('Log In Success');
}
else if(response === '2') {
alert('Incorrect Details');
}
else if(response === '3') {
alert('Fill In All Fields');
}
}
});
}
Any help is greatly appreciated.
Use This bro...
<form id="F_login" class="login-form">
<input type="text" name="email" placeholder="Email">
<input type="password" name="password" placeholder="Password">
<button id="btn_login" type="submit" class="btn trans login-button">Login</button>
</form>
$("#btn_login").click(function(){
var parm = $("#F_login").serializeArray();
$.ajax({
type: 'POST',
url: 'check-login.php',
data: parm,
success: function (response) {
if(response === '1') {
alert('Log In Success');
}
else if(response === '2') {
alert('Incorrect Details');
}
else if(response === '3') {
alert('Fill In All Fields');
}
},
error: function (error) {
alert("Login Fail...");
}
});
});
else if(response === '3') {
alert('Fill In All Fields');
}
}
});
}
It should run well...
Try this:
<form class="login-form">
<input type="text" name="email" placeholder="Email">
<input type="password" name="password" placeholder="Password">
<button class="btn trans login-button" onclick="check_login()">Login</button>
</form>
When the login submits, it will still try to reload the page, so you should remove the submit type and put the login function on the button
Attaching event listeners via tags is not a good practice and using jQuery for it it's cleaner and easier.
Try doing this:
$("form.login-form .login-button").click(function(e) {
e.preventDefault();
check_login();
});
Remember to remove this:
onSubmit="check_login();return false;
The statement check_login();return false will not work. You have to call return check_login(); and return false inside the function.
HTML
<form onsubmit="return check_login();">
<!-- input fields here -->
</form>
Javascript
function check_login() {
// Do your ajax call.
return false;
}
Right way is:
HTML Code:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
// Login function
$(function() {
$('.login-button').click(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'check-login.php',
data: $('form.login-form').serialize(),
success: function(response) {
if (response === '1') {
alert('Log In Success');
} else if (response === '2') {
alert('Incorrect Details');
} else if (response === '3') {
alert('Fill In All Fields');
}
}
});
});
})
</script>
<title>Ajax Login Form (Demo)</title>
</head>
<body>
<form class="login-form" name="login-form" method="POST" action="">
<input type="text" name="email" placeholder="Email" />
<input type="password" name="password" placeholder="Password" />
<button type="submit" class="btn trans login-button">Login</button>
</form>
</body>
</html>
Write your ajax code inside
$(document).ready(function(){
//
}); or
$(function(){
//
});
User Prevent Default to stop Form Submission
You can use 'serialize' function to make POST pram.
Remove the button type and use the onclick handler on it, not on the form.
It will also take care of the situation when it automatically submits on pressing enter key by accident.
Happy Coding !!!
there are a lot of way to do this:
write this code in your index:
index
use "eval" function in javascript instead of "alert" to show the reasult
it means that on your PHP code when the code receive the true inputs and there is a user in your database like the input, the PHP code echo javascript orders (bellow is your PHP codes that you send an ajax request to that):>
<?php if(response==1){
echo '$("link_reload").trigger("click");';
} ?>
and in your javascript use evel() instead of alert()
Try changing the input type from "submit" to a regular button whose onclick action is to call check_login()
The Ajax function for logging in and validating doesn't seem to get to the .php file for validation.
I'm new to both JS and Ajax and followed a few online tutorials, I then tried to implement this with what I had in place already and the problems started.
I've put an echo at the top of the page that Ajax calls, it never gets displayed. I've typed into url to be sure and it works fine. (displays the echo)
I've gone over the code a few times and can't see any obvious errors but then I'm not entirely certain of what I should be looking for.
If I leave the PHP in the 'header' of the HTML page it works fine but I understand this is bad practice. Grateful for any help.
HTML:
<form method="post" action="" id="ourLoginFormID_JS">
<div class="ourContactFormElement2">
<label for="username">Username:</label>
<input type="text" id="username" name="username" autocomplete="off" class="required" value="<?php if(isset($_POST['username'])) echo htmlentities($_POST['username']); ?>" />
</div>
<div class="ourContactFormElement2">
<label for="password">Password:</label>
<input type="password" id="password" name="password" autocomplete="off" class="required"/>
</div>
<div class="ourContactFormElement2">
<label> </label>
<input type="submit" name="loginButton" id="loginButton" value="Login!" onclick="validLogin()"/>
</div>
<div id="statusLogin"></div>
</form>
The Ajax:
function validLogin(){
$('.error').hide();
var username = $('#username').val();
if(username == ""){
$('label#usernameError').show();
$('input#username').focus();
return false;
}
$('.error').hide();
var password = $('#password').val();
if(password == ""){
$('label#passwordError').show();
$('input#password').focus();
return false;
}
var params = "username="+username+"&password="+password;
var url = "loginProcessAjax.php";
$("#statusLogin").show();
$("#statusLogin").fadeIn(400).html('<img src="image/loading.gif" />');
$.ajax({
type: 'POST',
url: url,
dataType: 'html',
data: params,
beforeSend: function() {
document.getElementById("statusLogin").innerHTML= 'checking...' ;
},
complete: function() {
},
success: function(html) {
$("#statusLogin").hide();
document.getElementById("statusLogin").innerHTML= html;
if(html=="success"){
window.location = "index.php"
}
}
});
}
PHP - I understand there may be some conflicting issues on this page but it doesn't get that far, however if you've any pointers that'd also be fantastic.
<?php
//check fields are filled in
echo "HULLOOOO!!!!!"; // doesn't display when run in function but ok from url
if(empty($_POST) === false){
$username = trim($_POST['username']);
$password = trim($_POST['password']);
//validate fields
if(empty($username) === true || empty($password) === true){
$errors[] = 'Your username and password are needed.';
}else if($users->userExists($username) === false){
$errors[] = 'That username does not exist';
}else if($users->emailActivated($username) === false){
$errors[] = 'You need to activate the account, please check your email.';
}else{
//start login
$login = $users->login($username, $password);
if($login === false){
$errors[] = 'That username or password is invalid';
//
// if(empty($errors) === false){
// echo '<p>' .implode('</p><p>', $errors).'</p>';
// }
}else{
//destroy old session and create new - prevents session fixation attacks
session_regenerate_id(true);
//all details are correct - the method returns the id to be sotred as a session
$_SESSION['id'] = $login;
//send user to their home page
echo "success";
header('Location: userHome.php');
exit();
}
}
}
Your data to the post request is not formatted in the right way. Use {'property1': 'value1', etc}.
First try to display the data with PHP, make it more complex when you're sure the connection between jQuery and PHP is working well.
Use Firebug or developer tools to see if there errors occur.
I have a form to login
<div class="fade_bg">
<div class="actionDiv">
<form id="login_form" action="./classes/login/Authenticator.php" method="post">
<p>username: <input type="text" name="username" /></p>
<p>password: <input type="password" name="password" /></p>
<p>
<input type="submit" name="adminLogin" value="Log in" id="adminLogin" />
<input type="submit" name="cancelLogin" value="Cancel" id="cancelLogin" />
</p>
</form>
</div>
</div>
Notice the form action is './classes/login/Authenticator.php.' The PHP script is by itself with no HTML or anything.
What I want is for an error message to display inside
<div class="actionDiv">
If the user enters an empty form or the wrong credentials. I've tried using AJAX, but it didn't work.
The login itself works. I just need to print the errors.
Here is the AJAX I used:
$('#adminLogin').on('click', function() {
$.ajax ({
type: 'post',
url: './classes/login/Authenticator.php',
dataType: 'text',
data: $('#login_form').serialize(),
cache: false,
success: function(data) {
if(data == 'invalid credentials')
$('body').html(data);
else
$('.fade_bg').fadeOut(200);
},
error: function(msg) {
alert('Invalid username or password');
}
});
});
The form is probably getting submitted by the browser. You can prevent the default action.
$('#login_form').submit(function(e){
e.preventDefault();
//perform ajax request here.
});
Prevent the submit button from submitting the form:
$('#adminLogin').on('click', function(event) {
event.preventDefault();
...
And if you want to display the return message in the .actionDiv, then do so in your ajax success callback:
if(data == 'invalid credentials')
$('.actionDiv').append($('<p/>').text(data));
...
For client side validation you need to check before $.ajax call this condition
You have to also give id to both input fields
$(document).ready(function(){
$('#adminLogin').on('click',function() {
//alert("hello");
var name = $("#username").val();
var error = 0 ;
if(name == ""){
$("#errUsername").fadeIn().text("Username required.");
$("#username").focus();
error++;
}
var password= $("#password").val();
if(password== ""){
$("#errPassword").fadeIn().text("Password required.");
$("#password").focus();
error++;
}
if(error > 0)
{
error = 0;
$('.actionDiv').append($('<p/>').text('invalid credentials'));
return false;
}
$.ajax ({
type: 'post',
url: 'login.php',
//dataType: 'text',
data: $('#login_form').serialize(),
cache: false,
success: function(data) {
alert(data);
if(data == 'invalid credentials')
{
$('.actionDiv').append($('<p/>').text(data));
return false;
}
},
error: function(msg) {
alert('Invalid username or password');
}
});
});
});
You need to add these two <span> tags near to Username and Password inputs respectively so that client side errors can be show in these two spans
Then on Server side When you check submitted form like
<?php
$uname = isset($_POST['username']) ? $_POST['username'] : "";
$pswd = isset($_POST['password']) ? $_POST['password'] : "";
//perform query operation whether Username with valid password is exist or not
if($notExist)
echo "invalid credentials";
else
echo "success";
?>
And when $.ajax response comes then you can inform user about invalid credentials in success like
if(data == 'invalid credentials')
$('.actionDiv').append($('<p/>').html(data));
So, I have a login form set in a lightbox. I want that when users click on submit, a function check if the username and password are correct before refreshing and go to the member page. It should also show the errors in the lightbox.
I have a problem with the jQuery part more particularly with the $.post function.
jQuery code:
$('#Connection form').submit('Connection',function(){
var Username = $('#UsernameConnection').val();
if(Username=="")
{
$('#UsernameConnection').css('border-color','red');
$('.ErrorUsernameConnection').text('Error 1');
Username = "Empty Field";
}else
if(Username=="Invalid")
{
$('#UsernameConnection').css('border-color','orange');
$('.ErrorUsernameConnection').text('Error 2');
Username = "Invalid field";
}
var Password = $('#Password Connection').val();
if(Password =="")
{
$('#Password Connection').css('border-color','red');
$('.ErrorPassword Connection').text('Error 3');
Password = "Empty field";
}
if((Username==true)&&(Password==true))
{
$.post('fonctions/connection.php',{VALUE1:VALUE2},function(connection)
{
$('.ConnectionError').text(connection);
if(connection=="ok")
{
return true;
}else
{
return false;
}
});
}else
{
return false;
}
});
});
PHP code:
if(isset($_POST['Connection']))
{
all the verifying function goes here.
}
and HTML:
<div id="Connection">
<div class="formConnection">
<form method="POST" autocomplete="off" name="Connection">
<label for="Connection">Username:</label><br/>
<input type="text" name="UsernameConnection" id="UsernameConnection"/><br/>
<span class="ErrorUsernameConnection"></span><br/>
<label for="Connection">Password:</label><br/>
<input type="password" name="PasswordConnection" id="PasswordConnection"/>
<span class="ErrorPasswordConnection"></span><br/>
<input type="checkbox" name="checkbox"/><label>Remember me</label><br/>
<input type="submit" name="Connection" value="Log In" id="Connection" class="LogIn"/>
</form>
</div>
</div>
My question are:
Is $.post the right function for this? If yes,:
Because the script only starts when users click in the submit button, is it necessary to create a new var in the jQuery just for the submit button?
Is the if(isset($_POST['Connection'])) part in the php necessary in this case or can I just put the function right away?
What should VALUE1 and VALUE2 be for this to work?
I think this is what you want to do:
$('#Connection form').submit('Connection',function(){
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", password: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
Basically, you can just serialize your form and post it to the page. Have the page send back a message (success or fail, 1 or 0) and then do something with that data.
I think you're over-complicating matters. You just want to post a form via AJAX—the easiest way to do this is as follows:
$('#login-form').submit(function() {
$.post('login.php', $(this).serialize(), function(response) {
// do something on success or failure here
});
return false;
});
Have your login.php echo a JSON object, or true or false, and display any errors in your lightbox or whatever.