I have the following situation:
index.html (which is my login page)
<div data-role="page" id="page_login">
<div id="wrapper_top_image">
<div id="top_image"></div>
</div>
<div data-role="content" data-theme="b">
<div id="landmark-1" data-landmark-id="1">
<form id="loginForm" onsubmit="return submitLogin();">
<div data-role="fieldcontain" class="ui-hide-label">
<label for="username">Username:</label>
<input type="text" name="username" id="username" value="" placeholder="Username" />
</div>
<div data-role="fieldcontain" class="ui-hide-label">
<label for="password">Password:</label>
<input type="password" name="password" id="password" value="" placeholder="Password" />
</div>
<input type="submit" value="Login" id="submitButton">
</form>
</div>
</div>
<div data-role="footer">
<h4>© 2013 Company</h4>
<h6>Developed by Alex</h6>
</div>
and then my PHP Script that is going to check everything -> ps.. I fixed to avoid injection already! :
auth.php
$mysqli = new mysqli($mysql_hostname,$mysql_user, $mysql_password, $mysql_database);
// Parse the log in form if the user has filled it out and pressed "Log In"
if (isset($_POST["username"]) && isset($_POST["password"])) {
$username =$_POST['username'];
$password =$_POST['password'];
$sql = "SELECT id, password, username FROM users WHERE username='$username' AND password='$password' LIMIT 1";
$result = $mysqli->query($sql) or die( $mysqli->error() );
$rowN= mysqli_num_rows($result);
if($rowN==1){
$response_array['status'] = 'success';
} else {
$response_array['status'] = 'error';
}
echo json_encode($response_array);
}
$mysqli->close();
Finally my JQuery Script:
function submitLogin(){
jQuery.support.cors = true;
$.ajax({
url: 'http://www.xxxx.com/mobile/auth.php',
crossDomain: true,
type: "post",
data: $("#loginForm").serialize(),
success: function(data){
if(data.status == 'success'){
//alert("Granted Access!");
$.mobile.changePage("main.html");
}else if(data.status == 'error'){
alert("Authentication Invalid. Please try again!");
navigator.app.exitApp();
$.mobile.changePage("index.html");
}
}
});
};
Everything is working ok! Data is checked and if it is okay, is redirected to main.html (main page) otherwise the app pops up a window saying that the authentication is wrong, keeping the user in the same page.
Here is the dilemma: If users type the wrong credential trying to login again, any credential that he/she enter will be considerate invalid even if he/she entered the right one and the app will keep going back to the login page until I refresh the browser or end the app in case of running in the device.
Does anyone knows what may be happening?
Related
I'm trying to send to my server 5 parameters:
Action: will contain the name of the form, in this case "signin"
Name: Name of the person who wants to signin
Surname: Surname of the person who wants to signin
Email: Email of the person who wants to signin
Password: Password of the person who wants to signin
the problem is that my server reads only 4 parameters: Name, Surname, Email and Password, and it don't see Action!
Here's the code:
Javascript:
function signin() {
alert("OK");
var action = $(this).attr('name'); // puts in action the name of the form (this case "signin")
$.ajax({
type: "POST",
url: "submit.php",
data: {
Action: action, // the server don't see it!!
Name: document.getElementById('signin-name').value, // Name in the form
Surname: document.getElementById('signin-surname').value, // // Surname in the form
Email: document.getElementById('singin-email').value, // Email in the form
Password: document.getElementById('singin-password').value // // Password in the form
},
cache: false,
success: function() {
alert("success");
window.location.href = "index.php"; // load the index.php page, which contains the login form
}
});
}
PHP - Signin.php:
<!-- Signin Form -->
<?php
require('include/header.php');
?>
<div class="limiter">
<div class="form-container">
<div class="form-wrap">
<form action="submit.php" method="post" name="form-signin" id="form-signin" autocomplete="off">
<span class="form-title">Registration form</span>
<div class="form-field">
<label for="Name">Name</label>
<input type="text" name="Name" id="signin-name" class="form-control" required pattern=".{1,100}" autofocus>
</div>
<div class="form-field">
<label for="Surname">Surname</label>
<input type="text" name="Surname" id="signin-surname" class="form-control" required pattern=".{1,100}" autofocus>
</div>
<div class="form-field">
<label for="email">Email address</label>
<input type="email" name="Email" id="signin-email" class="form-control" required>
</div>
<div class="form-field">
<label for="Password">New password</label>
<input type="password" name="Password" id="signin-password" placeholder="Almeno 6 caratteri" class="form-control">
</div>
<div id="display-error" class="alert alert-danger fade in"></div><!-- Display Error Container -->
<div class="form-submit-container">
<div class="form-submit-wrap">
<button class="form-cancel-button" type="submit">Cancel</button>
<button class="form-submit-button" type="submit" onclick="signin()">Signin</button>
</div>
</div>
</form>
</div>
</div>
</div>
<?php require('include/footer.php');?>
PHP - Submit.php:
<?php
#Detect AJAX and POST request, if is empty exit
if((empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') or empty($_POST)){
exit("Unauthorized Acces");
}
require('inc/config.php');
require('inc/functions.php');
# Check if Login form is submitted
if(!empty($_POST) && $_POST['Action'] === 'form-login'){
# Define return variable. for further details see "output" function in functions.php
$Return = array('result'=>array(), 'error'=>'');
$email = $_POST['Email'];
$password = $_POST['Password'];
/* Server side PHP input validation */
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$Return['error'] = "Please enter a valid Email address.";
} else if($password === '') {
$Return['error'] = "Please enter Password.";
}
if($Return['error']!='') {
output($Return);
}
# Checking Email and Password existence in DB
# Selecting the email address of the user with the correct login credentials.
$query = $db->query("SELECT Email FROM USERS WHERE Email='$email' AND Password='$password'");
$result = $query->fetch(PDO::FETCH_ASSOC);
if($query->rowCount() == 1) {
# Success: Set session variables and redirect to Protected page
$Return['result'] = $_SESSION['UserData'] = $result;
} else {
# Failure: Set error message
$Return['error'] = 'Invalid Login Credential.';
}
output($Return);
}
# Check if Registration form is submitted
if(!empty($_POST) && $_POST['Action'] === 'form-signin') {
# Define return variable. for further details see "output" function in functions.php
$Return = array('result'=>array(), 'error'=>'');
$name = $_POST['Name'];
$surname = $_POST['Surname'];
$email = $_POST['Email'];
$password = $_POST['Password'];
# Server side PHP input validation
if($name === '') {
$Return['error'] = "Please enter Full name.";
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$Return['error'] = "Please enter a valid Email address.";
} else if($password === '') {
$Return['error'] = "Please enter Password.";
}
if($Return['error']!='') {
output($Return);
}
# Check Email existence in DB
$result = $db->query("SELECT Email FROM USERS WHERE Name='$name' AND Surname='$surname' AND Email='$email'");
if($result->rowCount() == 1){
# Email already exists: Set error message
$Return['error'] = 'You have already registered with us, please login.';
}else{
# Insert the new user data inside the DB
try{
$db->query("INSERT INTO `users` (`ID_user`, `Name`, `Surname`, `Email`, `Password`) VALUES (NULL, '$name', '$surname', '$email', '$password')");
}
catch (PDOException $e) {
echo $e->getMessage();
}
# Success: Set session variables and redirect to Protected page
$Return['result'] = $_SESSION['UserData'] = $result;
}
output($Return);
}
PHP - Functions.php
# Function to set JSON output
function output($Return=array()){
header('Content-Type: application/json; charset=UTF-8');
#exit(json_encode($Return)); # Final JSON response
echo json_encode($Return);
}
here is a screenshot of the debugger:
Debug Screenshot
function signin() {
alert("OK");
var action = $('#form-signin').attr('name'); // puts in action the name of the form (this case "signin")
// alert(action);
$.ajax({
type: "POST",
url: "submit.php",
data: {
Action: action, // the server don't see it!!
Name: $('signin-name').val(), // Name in the form
Surname: $('signin-surname').val(), // // Surname in the form
Email: $('singin-email').val(), // Email in the form
Password: $('singin-password').val() // // Password in the form
},
cache: false,
success: function() {
alert("success");
window.location.href = "index.php"; // load the index.php page, which contains the login form
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="limiter">
<div class="form-container">
<div class="form-wrap">
<form action="submit.php" method="post" name="form-signin" id="form-signin" autocomplete="off">
<span class="form-title">Registration form</span>
<div class="form-field">
<label for="Name">Name</label>
<input type="text" name="Name" id="signin-name" class="form-control" required pattern=".{1,100}" autofocus>
</div>
<div class="form-field">
<label for="Surname">Surname</label>
<input type="text" name="Surname" id="signin-surname" class="form-control" required pattern=".{1,100}" autofocus>
</div>
<div class="form-field">
<label for="email">Email address</label>
<input type="email" name="Email" id="signin-email" class="form-control" required>
</div>
<div class="form-field">
<label for="Password">New password</label>
<input type="password" name="Password" id="signin-password" placeholder="Almeno 6 caratteri" class="form-control">
</div>
<div id="display-error" class="alert alert-danger fade in"></div><!-- Display Error Container -->
<div class="form-submit-container">
<div class="form-submit-wrap">
<button class="form-cancel-button" type="submit">Cancel</button>
<button class="form-submit-button" type="submit" onclick="signin()">Signin</button>
</div>
</div>
</form>
</div>
</div>
</div>
The problem is with your scope for $this. Since your Javascript is called within a BUTTON element, $this has a scope relative to the button, not the form. In trying to check what $this returns by itself, it says [object Window].
function signin() {
console.log(this);
}
Console:
[object Window]
You need to either pass this via signin(this) and backtrack to the containing form element if you plan on reusing the Javascript for other forms or just use the form id in place of this.
HTML:
<button onclick="signin(this)">
JS:
function signin(element) {
var action = element.form.getAttribute("name");
}
or just simply change the this to the form's id as Lakmal pointed out:
function signin() {
var action = $("#form-signin").attr("name");
}
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";
}
Hey guys I am creating a newsletter sign-up form and trying to submit it with AJAX..
Here is my form:
<div id="form-content">
<form method="POST" id="news-form" name="newsletter">
<div class="bd-input-2 form-group">
<input type="email" name="newsletter_email" placeholder="Enter your email address" required />
</div>
<div class="form-group">
<button type="submit" name="newsletter">Submit</button>
</div>
</form>
</div>
And this one is my JS file in same page as form:
$('#news-form').submit(function(e){
e.preventDefault();
$.ajax({
url: 'newsletter-submit.php',
type: 'POST',
data: $(this).serialize()
})
.done(function(data){
$('#form-content').fadeOut('slow', function(){
$('#form-content').fadeIn('slow').html(data);
console.log(data);
});
})
.fail(function(){
alert('Ajax Submit Failed ...');
});
});
On console nothing is displaying not even an error just an empty line.
And my newsletter-submit.php file :
<?php
if(isset($_POST['newsletter'])){
$newsletter_email = filter_var($_POST['newsletter_email'],FILTER_VALIDATE_EMAIL);
if(filter_var($newsletter_email, FILTER_VALIDATE_EMAIL)){
$newsletter_email = filter_var($newsletter_email, FILTER_VALIDATE_EMAIL);
$em_check = sqlsrv_query($con, "SELECT email FROM newsletter_signups WHERE email='$newsletter_email'",array(), array("Scrollable"=>"buffered"));
$num_rows = sqlsrv_num_rows($em_check);
if($num_rows > 0){
echo "<br/><p style='color: #fff;'>Email exist in our newsletter list.</p>";
}else{
$query = "INSERT INTO newsletter_signups (email) VALUES ('{$newsletter_email}')";
$insert_newsletter_query = sqlsrv_query($con,$query);
echo '<br/><p style="color: green;">Thank you for sign up in our newsletter</p>';
}
}
}
?>
But if I add any code after php tags e.g Hello world that is displayed after the submission.
My php code was working before AJAX file
Your input field is named newsletter_email and in your php you are checking for isset($_POST['newsletter']) which is always false.
For some reason, the "window.location.href" function does not work for me, can't seem to find out why.
This is the code from index.php:
<div class="dropdown-menu">
<div style="width: 300px;">
<div class="panel panel-primary">
<div class="panel-heading">Login</div>
<div class="panel-heading">
<label for="email">Email</label>
<input class="form-control" id="email" name="email" required />
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password" required />
<p><br/></p>
Forgotten Password<input type="button" class="btn btn-success" name="login" id="login" value="Login">
</div>
</div>
<div class="panel-footer"></div>
</div>
</div>
And this is the function in the "action.php" file that is mentioned in the jQuery function:
<?php
if(isset($_POST["userLogin"])){
$email = mysqli_real_escape_string($con, $_POST["userEmail"]);
$password = md5($_POST["userPassword"]);
$sql = "SELECT * FROM user_info WHERE email = '$email' AND password = '$password'";
$run_query = mysqli_query($con, $sql);
if($run_query===false){
echo mysqli_error($con);
} else {
$row = mysqli_fetch_array($run_query);
$_SESSION["uid"]= $row["user_id"];
$_SESSION["name"]= $row["first_name"];
echo "welcome";
}
}
?>
This is the jQuery with the AJAX function:
$(document).ready(function(){
$("#login").click(function(event){
event.preventDefault();
var email = $("#email").val();
var pass = $("#password").val();
$.ajax({
url : "action.php",
method : "POST",
data : {userLogin: 1, userEmail:email, userPassword:pass},
success : function(data){
if(data == "welcome"){
window.location.href = "profile.php";
}
/* alert(data);*/
}
});
});
});
notes:
As you can see in the jQuery function, there is this: "alert(data);". I wanted to look if it does work and put it on the screen without the "window.location.href" function to see that the "if" statement is correct, and it does work. Further more, when I go directly to the profile.php file, I see That the user is logged in, which means for me that the SQL functions is working fine, just it will not Re-Direct me to that (profile.php) page.
window.location.href expects an absolute url or a url relative to your domain (if it starts with a /).
If you only want to change the file part of your current path, you can use window.location.assign("profile.php")
If you want to redirect inside same domain
window.location.href = "/profile.php";
If you want to redirect to another domain
window.location.href = "http://www.antotherdomainname.com/profile.php";
These gets the username and password inputted by the user and is expected to be sent to the validate.php file to check whether the records is present in the database or not. and receives a response.
<script type="text/javascript">
function validatelogin() {
var user=document.forms["login"]["username"].value;
var pass=document.forms["login"]["password"].value;
if(user==null || user=="") {
alert("Please enter username");
$('#username').focus();
return false;
} else if(pass==null || pass=="") {
alert("Please enter password");
$('#password').focus();
return false;
} else if(user!==null || user!=="" || pass!==null || pass!=="") {
// These gets the username and password inputted by the user and is
// expected to be sent to the validate.php file to check whether the
// records is present in the database or not. and receives a response.
$.ajax({
url : "validate.php",
type : 'POST',
data : $('#login').serialize(),
success : function(msg) {
$('#login-box').html(msg);
}
});
return false;
} else {
alert("form submitted");
}
}
</script>
php file-used in querying the database to check existing records and is expected to trigger true or false response back to the ajax -please how can i do this.then from there the code can now decide whether to log in or not.
<?php
error_reporting(0);
mysql_pconnect("localhost","root","");
mysql_select_db("sim_tracker");
$username=$_POST['username'];
$password=$_POST['password'];
mysql_query("select * from tbl_user where
username='$username' and password='$password'");
$row=mysql_affected_rows();
if($row>0) {
return false;
echo"$username,$password";
}
?>
html
<div id="login-box" class="login-popup">
<a href="#" class="close">
<img src="images/close_pop.png" class="btn_close"
title="Close Window" alt="Close" />
</a>
<form method="post" id="login" class="signin"
action="#" onSubmit="return validatelogin()">
<fieldset class="textbox">
<label class="username">
<span>Username or email</span>
<input id="username" name="username" value=""
type="text" autocomplete="on" placeholder="Username">
</label>
<label class="password">
<span>Password</span>
<input id="password" name="password" value=""
type="password" placeholder="Password">
</label>
<button class="submit button" type="submit">Sign in</button>
<p>
<a class="forgot" href="#">Forgot your password?</a>
</p>
</fieldset>
</form>
</div>
I see at least 2 issues in your code:
mysql_affected_rows() will not refer to a select query, you're looking for mysql_num_rows()
your echo statement will never be executed because there's a return in front of it, so your script will in both cases (either the login information was correct or not) return absolutely nothing. So here's some better code:
$result = mysql_query("select * from tbl_user where username='$username' and password='$password'");
$row_count = mysql_num_rows();
if ($row_count > 0) {
// login correct, add some code to actually log the user in (i. e. some session stuff)
echo "You were logged in!"; // if you want just true or false say echo 1 instead
}
else {
// login incorrect
echo "Wrong username or password!" // or again echo 0
}