Firstly I'm not sure if missing anything in my code other than the problems in my functions, but i digress. I'm new to jquery so I'm having difficulty setting up a registration page. In the form I'm trying to check for valid entries as well as checking the queries in the back-end using php. I set up 2 files one is an html file and the other is a php file. Using ajax the function was supposed to call the php file, but I cant seem to get it working and I'm wondering if I should just put all the code in the same file. Furthermore I'm unsure if the functions are even working at all because its not returning any status. I will post the code for the two files below. Any hints or tips would be greatly appreciated.
The HTML file without css
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Register</title>
<link rel="stylesheet" href="assets/css/reset.css">
<link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
<script src="assets/js/jquery.min.js"> </script>
<script src="assets/js/main.js"> </script>
<div class="pen-title">
<h1>Registration Form</h1></div>
<script>
function emptyElement(x){
_(x).innerHTML = "";
}
function signup(){
var u = _("username").value;
var e = _("email").value;
var p1 = _("pass").value;
var p2 = _("pass2").value;
var status = _("status");
if(u == "" || e == "" || p1 == "" || p2 == ""){
status.innerHTML = "Fill out all of the form data";
} else if(p1 != p2){
status.innerHTML = "Your password fields do not match";
} else
{
_("submit").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "registration.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "signup_success"){
status.innerHTML = ajax.responseText;
_("submit").style.display = "block";
} else {
window.scrollTo(0,0);
_("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account.";
}
}
}
ajax.send("u="+u+"&e="+e+"&p="+p1);
}
}
</script>
<!-- Form Module-->
<div class="module form-module">
<div class="form">
</div>
<div class="form">
<h2>Create an account</h2>
<form method="post" name="signupform" id="signupform" onsubmit="return false;">
<input type="text" id="username" onfocus="emptyElement('status')" placeholder="Username" maxlength="50"/>
<input type="password" id="pass" onfocus="emptyElement('status')" placeholder="Password" maxlength="10"/>
<input type="password" id="pass2" onfocus="emptyElement('status')" placeholder="Confirm Password" maxlength="10"/>
<input type="email" id="email" onfocus="emptyElement('status')" placeholder="Email Address" maxlength="50"/>
<!-- <input type="tel" name="telephone" placeholder="Phone Number" maxlength="10"/> -->
<button type="submit" onclick="signup()" name="submit">Register</button>
</form>
</div>
</div>
</body>
</html>
The PHP file
<?php
// Connects to your Database
$host="myhost"; // Host name
$username="myuser"; // Mysql username
$password="mypass"; // Mysql password
$db_name="mydbname"; // Database name
$con = mysqli_connect("$host", "$username", "$password", "$db_name") or die(mysql_error());
// Ajax calls this REGISTRATION code to execute
if(isset($_POST["u"])){
// GATHER THE POSTED DATA INTO LOCAL VARIABLES
$u = preg_replace('#[^a-z0-9]#i', '', $_POST['u']);
$e = mysqli_real_escape_string($con, $_POST['e']);
$p = $_POST['p'];
// GET USER IP ADDRESS
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
// DUPLICATE DATA CHECKS FOR USERNAME AND EMAIL
$sql = "SELECT id FROM users WHERE username='$u' LIMIT 1";
$query = mysqli_query($con, $sql);
$u_check = mysqli_num_rows($query);
// -------------------------------------------
$sql = "SELECT id FROM users WHERE email='$e' LIMIT 1";
$query = mysqli_query($con, $sql);
$e_check = mysqli_num_rows($query);
// FORM DATA ERROR HANDLING
if($u == "" || $e == "" || $p == ""){
echo "The form submission is missing values.";
exit();
} else if ($u_check > 0){
echo "The username you entered is alreay taken";
exit();
} else if ($e_check > 0){
echo "That email address is already in use in the system";
exit();
} else if (strlen($u) < 3 || strlen($u) > 16) {
echo "Username must be between 3 and 16 characters";
exit();
} else if (is_numeric($u[0])) {
echo 'Username cannot begin with a number';
exit();
} else {
// END FORM DATA ERROR HANDLING
// Begin Insertion of data into the database
// Hash the password and apply your own mysterious unique salt
//$cryptpass = crypt($p);
//include_once ("php_includes/randStrGen.php");
//$p_hash = randStrGen(20)."$cryptpass".randStrGen(20);
// Add user info into the database table for the main site table
$sql = "INSERT INTO users (username, email, password, ip, signup, lastlogin, notescheck)
VALUES('$u','$e','$p' ,'$ip',now(),now(),now())";
$query = mysqli_query($con, $sql);
$uid = mysqli_insert_id($con);
// Establish their row in the useroptions table
$sql = "INSERT INTO useroptions (id, username, background) VALUES ('$uid','$u','original')";
$query = mysqli_query($db_conx, $sql);
// Create directory(folder) to hold each user's files(pics, MP3s, etc.)
//if (!file_exists("user/$u")) {
// mkdir("user/$u", 0755);
//}
}
}
?>
Your javascript code has many errors. Like you used _ instead of $ and your element Ids is wrong. They are not include #. So I have organized your code with your logic. Bu it is not a real question or it is not a true way to learn.
HTML
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Register</title>
<link rel="stylesheet" href="assets/css/reset.css">
<link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<!--script src="assets/js/main.js"> </script-->
<div class="pen-title">
<h1>Registration Form</h1></div>
<script>
function emptyElement(x){
$('#' + x).text("");
}
function signup(){
var un = $("#username").val();
var em = $("#email").val();
var p1 = $("#pass").val();
var p2 = $("#pass2").val();
if(un == "" || em == "" || p1 == "" || p2 == "")
{
$('#status').text("Fill out all of the form data");
}
else if(p1 != p2)
{
$('#status').text("Your password fields do not match");
}
else
{
$.ajax({
type: "POST",
url: "registration.php",
dataType: "json",
data : { u: un, p:p1, e:em },
cache: !1,
beforeSend: function(){
$("#submit").hide();
$('#status').text('please wait ...');
},
complete: function(){
$("#submit").show();
},
success: function(answer){
if(answer.result == "successful")
{
$("#status").html(answer.text);
}
else
{
$("#status").html(answer.result);
}
},
error: function(answer){
$("#status").text(answer);
}
});
}
/*
var ajax = ajaxObj("POST", "registration.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "signup_success"){
status.innerHTML = ajax.responseText;
$("submit").style.display = "block";
} else {
window.scrollTo(0,0);
$("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account.";
}
}
}
ajax.send("u="+u+"&e="+e+"&p="+p1);
*/
}
</script>
<!-- Form Module-->
<div class="module form-module">
<div class="form">
</div>
<div class="form">
<h2>Create an account</h2>
<form method="post" name="signupform" id="signupform" onsubmit="return false;">
<input type="text" id="username" onfocus="emptyElement('status')" placeholder="Username" maxlength="50"/>
<input type="password" id="pass" onfocus="emptyElement('status')" placeholder="Password" maxlength="10"/>
<input type="password" id="pass2" onfocus="emptyElement('status')" placeholder="Confirm Password" maxlength="10"/>
<input type="email" id="email" onfocus="emptyElement('status')" placeholder="Email Address" maxlength="50"/>
<!-- <input type="tel" name="telephone" placeholder="Phone Number" maxlength="10"/> -->
<button type="submit" onclick="signup()" name="submit">Register</button>
<div id="status"></div>
</form>
</div>
</div>
</body>
</html>
registration.php
<?php
$answer = new stdClass;
if(isset($_POST))
{
$answer->result = "successful";
$answer->text = "";
foreach($_POST as $key => $value)
{
$answer->text .= $key . ": " . $value . "<br />";
}
}
else
{
$answer->result = "Error";
$answer->text = "Error Message";
}
echo json_encode($answer);
?>
This registration.php is an example for you. You can rewrite with your logic.
You should use $answer object for response.
$answer->result is status of repsonse
$answer->text is response
I hope it will help you.
Related
I want to prevent form submission when email or username is not available (not found in database) or when passwords don't match.
(Password and "confirm password" don't match).
A similar question is asked here:
JavaScript code to stop form submission
The suggestion was to use a function that returns a boolean value and use it to determine if form should bw submitted or not.
I tried to make something similar usimg ajax but I couldn't return value from Ajax in the function.
Here's the PHP code that helps with checking if email or username exists.:
if (isset($_POST['username_check'])) {
$username = $_POST['username'];
$stmt = $db->prepare("SELECT count(*) as cntUser FROM Users WHERE username = :username");
$stmt->bindValue(':username', $username, PDO::PARAM_STR);
$stmt->execute();
$count = $stmt->fetchColumn();
if($count > 0){
echo "taken";
} else {
echo 'not_taken';
}
exit();
}
if (isset($_POST['email_check'])) {
$email = $_POST['email'];
$stmt = $db->prepare("SELECT count(*) as cntUser FROM Users WHERE email = :email");
$stmt->bindValue(':email', $email, PDO::PARAM_STR);
$stmt->execute();
$count = $stmt->fetchColumn();
if($count > 0) {
echo "taken";
} else {
echo 'not_taken';
}
exit();
}
Here's the HTML code with some javascript:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Register User</title>
</head>
<script>
// This code prints red or blue text on whether passwords match or not and return a boolean value
var check = function() {
var pass1 = document.getElementById("password").value;
var pass2 = document.getElementById("password2").value;
if (pass1 != "" && pass2 != "") {
if (pass1 === pass2) {
document.getElementById('message').style.color = 'green';
document.getElementById('message').innerHTML = 'matching';
return true;
} else {
document.getElementById('message').style.color = 'red';
document.getElementById('message').innerHTML = 'not matching';
return false;
}
}
else document.getElementById('message').innerHTML = '';
return false;
}
//If both passwords don't match, it should be impossible to submit form
function validate(){
var pass1 = document.getElementById("password").value;
var pass2 = document.getElementById("password2").value;
return check();
}
</script>
<body>
<h1>Register user</h1>
<form method="post" id="register_form" onsubmit="return validate();">
<label>Username:</label>
<div id="error_msg"></div>
<div>
<br><input type="text" name="username" value="" placeholder="User name" maxlength=30 required id="username" />
<span></span>
</div>
<div>
<br><label>First Name:</label>
<br><input type="text" name="firstname" value="" placeholder="First name" maxlength=45 required id="firstname" />
<br><label>Last name:</label>
<br><input type="text" name="lastname" value="" placeholder="Last name" maxlength=45 required id="lastname" />
<div>
<br><label>Epost:</label>
<br><input type="email" name="email" value="" placeholder="Email" maxlength=45 required id="email" />
<span></span>
</div>
<div>
<br><label>Password: </label>
<br><input type="password" name="password" required id="password" placeholder="Password" maxlength=60 value="" onkeyup='check();'>
<br><label>Confirm password:</label>
<br><input type="password" name="password2" required id="password2" placeholder="Confirm Password" maxlength=60 value="" onkeyup='check();'/>
<span></span><span id='message'></span>
<input type="hidden" value="{{ getMac("Register") }}" name="XSRFPreventionToken">
<br><input type="submit" name="register" id="reg_btn" value="Register"></form>
<script src="../jquery-3.5.0.js"></script>
<script src="../script.js"></script>
</body>
</html>
Here's the JavaScript code on script.js:
$('document').ready(function(){
var result = false;
var username_state = false;
var email_state = false;
var password_state = false;
$('#username').on('blur', function(){
var username = $('#username').val();
if (username == '') {
username_state = false;
return;
}
$.ajax({
url: 'process.php',
type: 'post',
data: {
'username_check' : 1,
'username' : username,
},
success: function(response){
if (response == 'taken' ) {
username_state = false;
$('#username').parent().removeClass();
$('#username').parent().addClass("form_error");
$('#username').siblings("span").text('Sorry... Username already taken');
}else if (response == 'not_taken') {
username_state = true;
$('#username').parent().removeClass();
$('#username').parent().addClass("form_success");
$('#username').siblings("span").text('Username available');
}
}
});
});
$('#email').on('blur', function(){
var email = $('#email').val();
if (email == '') {
email_state = false;
return;
}
$.ajax({
url: 'process.php',
type: 'post',
data: {
'email_check' : 1,
'email' : email,
},
success: function(response){
if (response == 'taken' ) {
email_state = false;
$('#email').parent().removeClass();
$('#email').parent().addClass("form_error");
$('#email').siblings("span").text('Sorry... Email already taken');
}else if (response == 'not_taken') {
email_state = true;
$('#email').parent().removeClass();
$('#email').parent().addClass("form_success");
$('#email').siblings("span").text('Email available');
}
}
});
});
//Check if everything is OK and submit form
$('#reg_btn').on('click', function(){
var username = $('#username').val();
var email = $('#email').val();
var password = $('#password').val();
if (username_state == false || email_state == false) {
$('#error_msg').text('Fix the errors in the form first');
$("#register_form").submit(function(e){
e.preventDefault();
});
} else $("#register_form").submit(function(e){
e.submit();
});
});
});
I can prevent login when passwords don't match. And I do get messages when email or username is not available. But I couldn't prevent form submission when email or username is not available.
(When you submit it just give error message, since I have "PK" and "unique keys" in my database tables that prevents duplicates of email and username).
How do I prevent form submission if (username_state == false || email_state == false) ?
You should set the listener to the form itself, not to the button of submitting.
$("#form_id_here").submit(function(e){
if (condition){
e.preventDefault();
}
});
I'm starting to learn Web Development and trying to build the login screen for my site.
Normally when the user logged in, he will be redirected to the Welcome page( which is the case before I work with all the Javascript). Now click Login will just refresh the page.
Here is my PHP file
<head>
<?php include $_SERVER['DOCUMENT_ROOT'] . "\include\header.php";?>
<title>Login</title>
<link rel="icon" type="image/png" href="http://localhost/image/login/navi.png"/>
</head>
<?php
// Initialize the session
session_start();
// Check if the user is already logged in, if yes then redirect him to welcome page
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true && time() < $_SESSION["expire"]){
header("location: http://localhost/main/welcome.php");
exit;
}
$email = $password = "";
$email_err = $password_err = "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate credentials
if(empty($email_err) && empty($password_err)){
// Prepare a select statement
$sql = "SELECT userid, username, email, password FROM users WHERE email = ?";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_email);
// Set parameters
$param_email = $email;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Store result
mysqli_stmt_store_result($stmt);
// Check if username exists, if yes then verify password
if(mysqli_stmt_num_rows($stmt) == 1){
// Bind result variables
mysqli_stmt_bind_result($stmt, $id, $username, $email, $hashed_password);
if(mysqli_stmt_fetch($stmt)){
if(password_verify($password, $hashed_password)){
// Password is correct, so start a new session
session_start();
// Store data in session variables
$_SESSION["loggedin"] = true;
$_SESSION["id"] = $id;
$_SESSION["username"] = $username;
$_SESSION['start'] = time(); // Taking now logged in time.
$_SESSION['expire'] = $_SESSION['start'] + (30 * 60);
// Redirect user to welcome page
header("location: http://localhost/main/welcome.php");
} else{
// Display an error message if password is not valid
$password_err = "Wrong password";
}
}
} else{
// Display an error message if username doesn't exist
$email_err = "Wrong email";
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
// Close statement
mysqli_stmt_close($stmt);
}
}
// Close connection
mysqli_close($link);
}
?>
<body class="background">
<div class="bgoverlay">
<div class="login-container">
<div class="wrap-login">
<span class="login-form-title">
Account Login
</span>
<form class="login-form login-validate-form" >
<div id="email" class="login-wrap-input login-validate-input" data-validate = "Enter email">
<input class="login-input" type="text" name="email" placeholder="Email">
<span class="login-focus-input" data-placeholder=""></span>
</div>
<div class="login-wrap-input login-validate-input" data-validate="Enter password">
<input id="password" class="login-input" type="password" name="password" placeholder="Password">
<span class="login-focus-input" data-placeholder=""></span>
<span toggle="#password" class="login-show-pass see toggle-password"></span>
</div>
<div class="container-login-form-btn">
<?php
if($email_err != null || $password_err !=null) {
echo '<script type="text/javascript">alert("'.$email.$password.'");</script>';
}
?>
<input type="submit" class="login-form-btn" value="Login">
</div>
</form>
</div>
</div>
</div>
<div id="dropDownSelect1"></div>
<script src="http://localhost/root/js/jquery-3.5.0.min.js"></script>
<script src="http://localhost/root/js/login.js?<?php echo(rand(0,999999));?>"></script>
</body>
</html>
*I honestly don't know which part to give so I think it's best to just put them all just in case.
Here is the Javascript that I have been fixing
(function ($) {
"use strict";
/*==================================================================
[ Focus input ]*/
$('.login-input').each(function(){
$(this).on("blur", function(){
if($(this).val().trim() != "") {
$(this).addClass('login-has-val');
}
else {
$(this).removeClass('login-has-val');
}
})
})
/*==================================================================
[ Validate ]*/
var input = $('.login-validate-input .login-input');
function validate (input) {
if($(input).attr('type') == 'email' || $(input).attr('name') == 'email') {
if($(input).val().trim().match(/^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{1,5}|[0-9]{1,3})(\]?)$/) == null) {
return false;
}
}
else {
if($(input).val().trim() == ''){
return false;
}
}
}
$('.login-validate-form').on('submit',function(){
var check = true;
for(var i=0; i<input.length; i++) {
if(validate(input[i]) == false){
showValidate(input[i]);
check=false;
}
}
return check;
});
$('.login-validate-form .login-input').each(function(){
$(this).focus(function(){
hideValidate(this);
});
});
function showValidate(input) {
var thisAlert = $(input).parent();
$(thisAlert).addClass('login-alert-validate');
}
function hideValidate(input) {
var thisAlert = $(input).parent();
$(thisAlert).removeClass('login-alert-validate');
}
/*==================================================================
[ Show pass ]*/
jQuery(document).ready(function() {
jQuery(".show-pass").hide();
});
jQuery("#password").change(function() {
if(this.value.replace(/\s/g, "") === "") {
jQuery(".show-pass").hide();
} else {
jQuery(".show-pass").show();
}
});
jQuery(".show-pass").change(function() {
jQuery("#password").val("");
jQuery(this).hide();
});
$(".toggle-password").click(function() {
$(this).toggleClass("unsee");
var input = $($(this).attr("toggle"));
if (input.attr("type") == "password") {
input.attr("type", "text");
} else {
input.attr("type", "password");
}
});
})(jQuery);
This is what the URL look like after pressed Login
Look at your PHP code, you taking in consideration the request should be POST
if($_SERVER["REQUEST_METHOD"] == "POST") ...
and your HTML markup for your form has no method, which is by default going to be GET.
You need to edit you form tag to be like this
<form class="login-form login-validate-form" method="post" action="URL.php">
It's possible that your are not choosing the correct path, please reconfirm the correct path or you can try changing your header to:
header("location:welcome.php");
I'm doing a log in page, i have javascript doing validations ( checking if field is blank) sql storing the data and php doing what php does (idk).... anyway when I press submit it tells me Cannot POST /login.php
is there away to test it on a website and see if it actually works or is the code completely wrong.
<?php
$server = 'localhost';
$username = 'root';
$passowrd = 'cosc_453';
$dbname = 'login'
if(!empty($_POST['user']))
{ $query = mysql_query("SELECT * FROM UserName where userName ='$_POST[user]' AND pass = '$_POST[pass]'") or die(mysql_error());
$row = mysql_fetch_array($query) or die(mysql_error());
{ $_SESSION['userName'] = $row['pass']; echo "SUCCESSFULLY LOGIN TO USER PROFILE PAGE..."; }
else { echo "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY...";
}
}
}
if(isset($_POST['submit']))
{ SignIn();
} ?>
php external
function validate(){
if ( document.getElementById (user).value=="")
{
alert ("Please enter your user name");
}
else if ( document.getElementById(pass).value=="")
alert("Please enter you password");
else {
alert("Processing Login........");
}
}
javscript external
CREATE TABLE UserName (
UserNameID int(9) NOT NULL auto_increment,
userName VARCHAR(40) NOT NULL,
pass VARCHAR(40) NOT NULL,
PRIMARY KEY(UserNameID) );
INSERT INTO
UserName (userName, pass)
VALUES
("cosc" , "453");
sql external
<!DOCTYPE HTML>
<html>
<head>
<title>Sign-In</title>
<link rel="stylesheet" type="text/css" href="home.css">
<script src ="login.js"></script>
</head>
<body id="body-color">
<div id="Sign-In">
<fieldset style="width:30%">
<legend>LOG-IN HERE</legend>
<form method="Post" action="login.php" submit =" validate()">
User:<br><input type="text" name="user" size="40"><br>
Password:<br><input type="password" name="pass" size="40"><br>
<input id="button" type="submit" name="submit" value="Log-In">
</form>
< /fieldset>
</div>
</body>
</html>
Your mysql do not have a connection to database. And please stop using mysql, use mysqli instead
<?php
$con = mysqli_connect("localhost","root","cosc_453","login");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM UserName WHERE userName ='".$_POST[user]."' AND pass = '".$_POST[pass]."'";
$result = mysqli_query($conn,$sql);
$count_result = mysqli_num_rows($result);
// Login Success URL
if($count_result == 1)
{
// If you validate the user you may set the user cookies/sessions here
#setcookie("logged_in", "user_id");
#$_SESSION["logged_user"] = "user_id";
$_SESSION["secret_id"] = $row['secret_id'];
if($row['level'] == 1)
{
// Set the redirect url after successful login for admin
$resp['redirect_url'] = 'admin/';
}
else if($row['level'] == 2)
{
// Set the redirect url after successful login for user
$resp['redirect_url'] = 'user/';
}
}
else
{
echo "Invalid username or pass";
}
?>
To add onto what Eh Ezani stated, you have an issue in your HTML. Your form attribute reads submit when I believe what you meant is onsubmit. Might want to try something like.
<form method="Post" action="login.php" onsubmit ="return validate()">
User:<br><input type="text" name="user" size="40"><br>
Password:<br><input type="password" name="pass" size="40"><br>
<input id="button" type="submit" name="submit" value="Log-In">
</form>
Also, "Use MySQLi over the older MySQL functions. The "i" stands for "improved". The list of improvements can be found in the docs.
-credited to
Difference between mysqli and mysql?
I have followed two seperate Ajax tutorials online to try and make my login form not redirect to another page when there are error messages. However, neither of the methods seem to be working and my form still directs to another page and shows the error messages there. I don't understand what the problem is as I have pretty much followed the tutorials directly and it works for them but not me.
Below is the code for my form:
<form id= "login_form" action="login.php" method="post">
<span id="login_errors"></span>
<label>Email Address</label>
<input type="text" name="email" id="email" required="required"/>
<br />
<label>Password</label>
<input type="password" name="password" id="password" required="required"/>
<br />
<div class="checkbox">
<input id="remember" type="checkbox" />
<label for="remember">Keep me signed in</label>
</div>
<div class="action_btns">
<div class="one_half last"><input type="submit" class="btn btn-blue" id="login_button" value="Login"></div>
<div class="one_half last">Sign up</div>
</div>
</form>
and here is the ajax code based on one of the tutorials I follwed:
$("#login_button").click(function(){
$.post($("#login_form").attr("action"), $("#login_form:input").serializeArray(), function(info){$("#login_errors").html(info);});
});
$("login_form").submit(function(){
return false;
});
here is the code for the other tutorial that also didn't work:
$("#login_button").click(function(){
var action = $("#login_form").attr("action");
var form_data = {
email: $("#email").val(),
password: $("#password").val(),
is_ajax: 1
};
$.ajax({
type:"POST",
url:"action",
data: form_data,
success: function(response){
if(response == 'success'){
$("#login_errors").html("successful!");
}else{
$("#login_errors").html("unsuccessful!");
}
}
});
});
I have included Jquery at the top of my webpage:
<script type="text/javascript" src="jquery-1.11.0.min.js"></script>
and also linked my ajax file beneath that too at the top of the page.
<script type="text/javascript" src="login_Ajax.js"></script>
There is a typo in the second ajax code: the url parameter should instead of url: "action", look like this:
url: action,
without quotes, as it refers to the variable declared a few lines above.
Not sure if this solves your problem, but to see the whole picture you should also show your "login.php".
for the first code you seems to have forgotten to put #
$("#login_form").submit(function(){
return false;
});
for second you seems to have entered invalid url
url:"action"
it should be jugging from your HTML
url:"login.php"
Complete solution to your problem: Since you were following a tutorial since you were following different tutorials and mixing codes, Let me give you a freash and simple one;
Dont forget the jquery library at the top e.g.
<script type="text/javascript" src="jquery-1.11.0.min.js"></script>
<script>
So copy this to a page e.g login.php page
<script type="text/javascript" src="jquery-1.11.0.min.js"></script>
<script>
$(function(){
$(document).on("click", ".ylogButton", function(e) {
e.preventDefault();
//validate
var email = $("#inputEmail").val();
var password = $("#inputPassword").val();
var emailp = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (email=='')
{
alert("Please enter your login email");
}
else if (password=='')
{
alert("Please enter password");
}
else {
//Built a url to send
var info = $("#yloginform").serialize();
$.ajax({
type: "POST",
url: "authenticate.php",
data: info,
success: function(result){
$("#loginmsg").html(result);
//$("#form")[0].reset();
}
});
e.preventDefault();
}
});
});
</script>
<div id="loginmsg"></div>
<form class="form-signin" id="yloginform">
<h2 style="text-align:center;"> sign in </h2>
<label for="inputEmail" class="sr-only">Login username</label>
<input type="text" id="inputEmail" name="email" class="form-control" placeholder="login email" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" name="password" id="inputPassword" class="form-control" placeholder="Password" required>
<button class="ylogButton" type="submit">Sign in</button>
</form>
Then open another file called authenticate.php and copy this login php code
<?php
//connection to db
$hostname_localhost = "localhost";
$database_localhost = "dbname"; //db name
$username_localhost = "root";
$password_localhost = ""; //db password if any
$localhost = mysql_pconnect($hostname_localhost, $username_localhost, $password_localhost) or trigger_error(mysql_error(),E_USER_ERROR);
?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
if (PHP_VERSION < 6) {
$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
}
$theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
switch ($theType) {
case "text":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "long":
case "int":
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
break;
case "double":
$theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
break;
case "date":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "defined":
$theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
break;
}
return $theValue;
}
}
?>
<?php
if (isset($_POST["email"])) {
$email = $_POST['email'];
$password = $_POST['password'];
}
//login registered user, but we always assume session has not been started
if (!isset($_SESSION)) {
session_start();
}
//this is just some magic
$loginFormAction = $_SERVER['PHP_SELF'];
if (isset($_GET['accesscheck'])) {
$_SESSION['PrevUrl'] = $_GET['accesscheck'];
}
if (isset($_POST['email'])) {
$loginUsername=$_POST['email'];
$password=$_POST['password'];
$MM_fldUserAuthorization = "userlevel";
$MM_redirectLoginSuccess = "$return_url";
$MM_redirectLoginFailed = "$return_url";
$MM_redirecttoReferrer = false;
mysql_select_db($database_localhost, $localhost);
$LoginRS__query=sprintf("SELECT email, password, userlevel FROM users WHERE email='$loginUsername' AND password='$password'");
$LoginRS = mysql_query($LoginRS__query, $localhost) or die(mysql_error());
$loginFoundUser = mysql_num_rows($LoginRS);
if ($loginFoundUser) {
$loginStrGroup = mysql_result($LoginRS,0,'userlevel');
if (PHP_VERSION >= 5.1) {session_regenerate_id(true);} else {session_regenerate_id();}
//declare two session variables and assign them
$_SESSION['MM_Username_check'] = $loginUsername;
$_SESSION['MM_UserGroup'] = $loginStrGroup;
if (isset($_SESSION['PrevUrl']) && false) {
$MM_redirectLoginSuccess = $_SESSION['PrevUrl'];
}
echo "welcome, $lastname ";
$redirectpage = "sucesspage.php";
echo "<script>window.location.href='$redirectpage';</script>";
}
else {
echo "wrong username or password";
}
}
else
{
$text = "Error! Please try again.";
}
?>
Then ensure in your database you have
columns email, password and userlevel
The above code will generate session variable <?php $_SESSION['MM_Username_check'] ?> that will be the email of a logged in user.
And when your login is successful you will be redirected to successpage.php
Im creating login script which are based on javascript and PHP. But I had problem with it.
Whatever I send via form I will be redirected to user.php?u=loginfailed. It doesen't matter whether it is properly email and password (which I have in my database). As you can see page "user.php?u=X" should be open only when email and password are entered correctly. But in my case when I sent correct data and incorrect data it will be the same... To sum up - correct data should redirected me to user.php?u=X and incorrect should display an error message below the form.
What do you think about it?
Index.php
<?php
if(isset($_POST["e"])){
include_once("../db/db_fns.php");
$e = mysqli_real_escape_string($db_conx, $_POST['e']);
$p = md5($_POST['p']);
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
if($e == "" || $p == ""){
echo "loginfailed";
exit();
} else {
$sql = "SELECT id, username, password FROM users WHERE email='$e' AND activated='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
$db_id = $row[0];
$db_username = $row[1];
$db_pass_str = $row[2];
if($p != $db_pass_str){
echo "loginfailed";
exit();
} else {
$_SESSION['userid'] = $db_id;
$_SESSION['username'] = $db_username;
$_SESSION['password'] = $db_pass_str;
setcookie("id", $db_id, strtotime( '+30 days' ), "/", "", "", TRUE);
setcookie("user", $db_username, strtotime( '+30 days' ), "/", "", "", TRUE);
setcookie("pass", $db_pass_str, strtotime( '+30 days' ), "/", "", "", TRUE);
$sql = "UPDATE users SET ip='$ip', lastlogin=now() WHERE username='$db_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
echo $db_username;
exit();
}
}
exit();
}
?>
<script src="../js/main.js"></script>
<script src="../js/ajax.js"></script>
<script src="login.js"></script>
<form id="loginform" onsubmit="return false;">
<div>Email Address:</div>
<input type="text" id="email" onfocus="emptyElement('status')" maxlength="88">
<div>Password:</div>
<input type="password" id="password" onfocus="emptyElement('status')" maxlength="100">
<br /><br />
<button id="loginbtn" onclick="login()">Log In</button>
<p id="status"></p>
Forgot Your Password?
</form>
login.js
function emptyElement(x) {
_(x).innerHTML = "";
}
function login() {
var e = _("email").value;
var p = _("password").value;
if (e == "" || p == "") {
_("status").innerHTML = "Fill out all of the form data";
} else {
_("loginbtn").style.display = "none";
_("status").innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "index.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "loginfailed") {
_("status").innerHTML = "Login unsuccessful, please try again.";
_("loginbtn").style.display = "block";
} else {
window.location = "user.php?u="+ajax.responseText;
}
}
}
ajax.send("e="+e+"&p="+p);
}
}
Try this :
Try to alert ajax.responseText and see if it return proper result without an error. Also user trim before comparing responsetext like this : if(ajax.responseText.trim() == "loginfailed")
Why you are not using Jquery as it is very simple and easy to use.
I believe you are missing return and therefore your form is submitting regardless. Don't forget to have the login() function return false so it doesn't submit.
try <button id="loginbtn" onclick="return login();">Log In</button>