I am newbie in php, kindly pardon me if I looks silly. I am still learning step by step with the help of online forums and stack community.
I have a form online which code is as below:
<?php
define('DIR_APPLICATION', str_replace('\'', '/', realpath(dirname(__FILE__))) . '/');
include(DIR_APPLICATION."config.php");
ob_start();
session_start();
$msg = 'none';
$sql = '';
if(isset($_POST['email']) && $_POST['email'] != '' && isset($_POST['password']) && $_POST['password'] != ''){
if($_POST['usertype'] == 'admin'){
//here for admin
$sql= mysql_query("SELECT * FROM admin WHERE a_email = '".make_safe($_POST['email'])."' and password = '".make_safe($_POST['password'])."'",$link);
}
else if($_POST['usertype'] == 'teacher'){
//here for teacher
$sql= mysql_query("SELECT * FROM teacher WHERE t_email = '".make_safe($_POST['email'])."' and t_password = '".make_safe($_POST['password'])."'",$link);
}
else if($_POST['usertype'] == 'student'){
//here for student
$sql= mysql_query("SELECT * FROM student WHERE s_email = '".make_safe($_POST['email'])."' and s_password = '".make_safe($_POST['password'])."'",$link);
}
else if($_POST['usertype'] == 'parents'){
//here for parent
$sql= mysql_query("SELECT * FROM parent WHERE p_email = '".make_safe($_POST['email'])."' and p_password = '".make_safe($_POST['password'])."'",$link);
}
else if($_POST['usertype'] == 'librarian'){
//here for employee
$sql= mysql_query("SELECT * FROM user WHERE u_email = '".make_safe($_POST['email'])."' and u_password = '".make_safe($_POST['password'])."'",$link);
}
else if($_POST['usertype'] == 'accountant'){
//here for employee
$sql= mysql_query("SELECT * FROM user WHERE u_email = '".make_safe($_POST['email'])."' and u_password = '".make_safe($_POST['password'])."'",$link);
}
if($row = mysql_fetch_array($sql)){
//here success
$_SESSION['objLogin'] = $row;
$_SESSION['login_type'] = $_POST['usertype'];
if($_POST['usertype'] == 'admin'){
header("Location: dashboard.php");
die();
}
else if($_POST['usertype'] == 'teacher'){
header("Location: t_dashboard.php");
die();
}
else if($_POST['usertype'] == 'student'){
header("Location: s_dashboard.php");
die();
}
else if($_POST['usertype'] == 'parents'){
header("Location: p_dashboard.php");
die();
}
else if($_POST['usertype'] == 'accountant'){
header("Location: a_dashboard.php");
die();
}
else if($_POST['usertype'] == 'librarian'){
header("Location: l_dashboard.php");
die();
}
}
else{
$msg = 'block';
}
}
function make_safe($variable)
{
$variable = strip_tags(mysql_real_escape_string(trim($variable)));
return $variable;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>SITE TITLE | Log in</title>
<!-- Tell the browser to be responsive to screen width -->
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<!-- Bootstrap 3.3.5 -->
<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<!-- Ionicons -->
<link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
<!-- Theme style -->
<link rel="stylesheet" href="dist/css/AdminLTE.min.css">
<!-- iCheck -->
<link rel="stylesheet" href="plugins/iCheck/square/blue.css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body class="hold-transition login-page">
<div class="login-box">
<div class="login-logo">
<b>SITE</b> TITLE
</div>
<!-- /.login-logo -->
<div class="login-box-body">
<p class="login-box-msg">Sign in to start your session</p>
<form onSubmit="return validationForm();" role="form" id="form" method="post">
<div class="form-group has-feedback">
<input type="email" name="email" id="email" class="form-control" placeholder="Email">
<span class="glyphicon glyphicon-envelope form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<input type="password" name="password" id="password" class="form-control" placeholder="Password">
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<select class="form-control" name="usertype" id="usertype">
<option value="-1">-- Select User Type --</option>
<option value="admin">Admin</option>
<option value="teacher">Teacher</option>
<option value="student">Student</option>
<option value="parents">Parents</option>
<option value="accountant">Accountant</option>
<option value="librarian">Librarian</option>
</select>
</div>
<div class="row">
<div class="col-xs-8">
Forget Password?<br>
</div>
<!-- /.col -->
<div class="col-xs-4">
<button type="submit" id="login" class="btn btn-primary btn-block btn-flat">Sign In</button>
</div>
<!-- /.col -->
</div>
</form>
</div>
<!-- /.login-box-body -->
</div>
<!-- /.login-box -->
<!-- jQuery 2.2.0 -->
<script src="plugins/jQuery/jQuery-2.2.0.min.js"></script>
<!-- Bootstrap 3.3.5 -->
<script src="bootstrap/js/bootstrap.min.js"></script>
<!-- iCheck -->
<script src="plugins/iCheck/icheck.min.js"></script>
<script>
$(function () {
$('input').iCheck({
checkboxClass: 'icheckbox_square-blue',
radioClass: 'iradio_square-blue',
increaseArea: '20%' // optional
});
});
</script>
<script type="text/javascript">
function validationForm(){
if($("#email").val() == ''){
alert("Email Required !!!");
$("#email").focus();
return false;
}
else if($("#password").val() == ''){
alert("Password Required !!!");
$("#password").focus();
return false;
}
else if($("#usertype").val() == '-1'){
alert("Select User Type !!!");
return false;
}
else{
return true;
}
}
</script>
<!-- SCRIPTS -AT THE BOTOM TO REDUCE THE LOAD TIME-->
<!-- JQUERY SCRIPTS -->
<script src="assets/js/jquery-1.10.2.js"></script>
<!-- BOOTSTRAP SCRIPTS -->
<script src="assets/js/bootstrap.min.js"></script>
</body>
</html>
This form works perfectly.
But my issue is I am creating an android form for this online version where I need a json response. So I tried the following in the browser:
mydomain.com/index.php?email=user#example.com&password=mypass&usertype=student
This results in the same page.
I am confused why this is not entering the page.
I can understand that somewhere I am wrong but can't figure it out.
Kindly help please.
As #Akhil #Vijay and #MiguelJimenez suggested
I changed $_POST to $_REQUEST and it worked like a charm
So, if any one getting stuck in this issue this might help you guys hopefully.
Related
This question already has answers here:
Row count with PDO
(21 answers)
Closed 2 years ago.
The login page to an admin dashboard - index.php, with every aspect of the site is working perfectly locally, but when i uploaded it on a web server, my login page keeps throwing the Seems you have not registered. error. I have imported the database accordingly and edited the database connection file to reflect that of the web server. I have gone through the code severally. All the suggestions i saw online didn't help.
I saw somewhere that steep difference in php versions might be the cause. My WAMP is running a php version of 7.0.10 while the web server is running a 7.2.31. Does that count?
I hosted the site on 000webhost - if that would be on any help.
I have attached my index.php and my database connection file (with the new web server details)
index.php
<?php
//index.php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
include("./database/dbnew.php");
if (isset($_SESSION["usertype"])) {
header("location:dashboard.php");
}
$message = '';
if(isset($_POST["login"])) {
$query = "SELECT * FROM user WHERE email = :email";
$statement = $connect->prepare($query);
$statement->execute( array('email' => $_POST["user_email"]) );
$count = $statement->rowCount();
if($count > 0) {
$result = $statement->fetchAll();
foreach($result as $row) {
if(password_verify($_POST["user_password"], $row["password"])) {
if($row['user_status'] == 'Active') {
$_SESSION['usertype'] = $row['usertype'];
$_SESSION['userid'] = $row['id'];
$_SESSION['username'] = $row['username'];
$_SESSION['last_login'] = $row['last_login'];
$_SESSION['user_status'] = $row['user_status'];
header("location:dashboard.php");
} else {
$message = "<label>Your account is disabled, Please contact the administrator</label>";
}
} else {
$message = '<div class="alert alert-danger">Wrong Email Address/Password Combination</div>';
}
}
} else {
$message = '<div class="alert alert-warning">Seems you have not registered yet</div>';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Inventory Management System</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="./includes/style.css">
<script type="text/javascript" rel="stylesheet" src="./js/main.js"></script>
</head>
<body>
<div class="overlay"><div class="loader"></div></div>
<!-- Navbar -->
<br/><br/>
<div class="container">
<h3 align="center">Blessed Pharmacy Inventory </h3>
<div class="card mx-auto" style="width: 20rem;">
<img class="card-img-top mx-auto" style="width:60%;" src="./images/login.png" alt="Login Icon">
<div class="card-body">
<form method="post">
<?php echo $message; ?>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" name="user_email" id="user_email" placeholder="Enter email" required>
<small id="e_error" 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" name="user_password" id="user_password" placeholder="Password" required>
<small id="p_error" class="form-text text-muted"></small>
</div>
<div class="form-group">
<button type="submit" name="login" value="Login" class="btn btn-primary"><i class="fa fa-lock"> </i>Login</button>
</div>
<!-- <span>Register</span> -->
</form>
<!-- </div>
<div class="card-footer">Forget Password ?</div>
</div> -->
</div>
</body>
</html>
dbnew.php
<?php
//database_connection
$connect = new PDO('mysql:host=localhost;xxxxxxxxxxx_inv_db', 'xxxxxxxxxxx_root', 'xxxxxxxxxxx_password');
session_start();
?>
PDO's rowCount() method is notoriously flakey when used with SELECT statements. It's intended for INSERTs, UPDATEs, and DELETEs.
Refactor it out ... something like this.
$count = 0
$result = $statement->fetchAll();
foreach($result as $row) {
$count++
if(password_verify($_POST["user_password"], $row["password"])) {
if($row['user_status'] == 'Active') {
$_SESSION['usertype'] = $row['usertype'];
$_SESSION['userid'] = $row['id'];
$_SESSION['username'] = $row['username'];
$_SESSION['last_login'] = $row['last_login'];
$_SESSION['user_status'] = $row['user_status'];
header("location:dashboard.php");
} else {
$message = "<label>Your account is disabled, Please contact the administrator</label>";
}
} else {
$message = '<div class="alert alert-danger">Wrong Email Address/Password Combination</div>';
}
} /* end foreach($result as $row) */
if ($count == 0) {
$message = '<div class="alert alert-warning">Seems you have not registered yet</div>';
}
elseif ($count > 1) {
$message = '<div class="alert alert-danger">More than one email match!!! Should not happen!!!</div>';
}
I have a problem with trim, it doesnt work as i expected, when the user writes only spaces in username form ("studentname") it should write you didint fill all fields ("niste izpolnili vsa polja") and i dont know how to achieve that, sorry if question is duplicate but i didnt find the answer to fix my problem
here is the code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>vaja 5: PHP</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="container">
<form name='form' method='post'>
<label class="registracija">Registracija</label>
<div class="form-group row">
<label for="username" class="col-sm-2">Vnesi ime</label>
<div>
<input type="text" id="studentname" name="studentname">
</div>
</div>
<div class="form-group row">
<label for="password" class="col-sm-2">Vnesi geslo</label>
<div>
<input type="password" id="password1" name="password1">
</div>
</div>
<div class="form-group row">
<label for="password" class="col-sm-2">Geslo še enkrat</label>
<div>
<input type="password" id="password2" name="password2">
</div>
</div>
<div>
<input type="submit" value="Pritisni me" name="button">
</div>
</form>
</div>
<p>
<div class="container">
<?php
if (isset($_POST["button"]))
{
echo $_POST['studentname'];
}
?>
<br>
<?php
if (isset($_POST["button"])) {
$studentname = trim( $_POST['studentname'] );
$password1 = $_POST ['password1'];
$password2 = $_POST ['password2']; }
if ($_POST['studentname'] == "" || $_POST['password1'] == "" || $_POST['password2'] == "") {
echo "Niste izpolnili vsa polja";
} else
if ($_POST['password1']!= $_POST['password2']) {
echo "Gesli se ne ujemata";
} else {
echo "Registracija uspela";
}
?>
<div>
</p>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>
You register a variable $studentname with the trim result but you actually compare to $_POST['studentname']. Try to use $studentname === "".
if (trim($_POST['studentname']) == "" || $_POST['password1'] == "" || $_POST['password2'] == "") {
echo "Niste izpolnili vsa polja";
I would enhance the following to trim all input fields, not just the studentname
if (isset($_POST["button"])) {
$studentname = trim($_POST['studentname']);
$password1 = trim($_POST['password1']);
$password2 = trim($_POST['password2']);
}
Then make sure write your conditions on the variables, not the original POSTed values. This is the main issue in your current code.
I also rewrote your else/if to be a bit more clear.
// ensure that user submitted all fields
if (
studentname == ''
|| $password1 == ''
|| $password2 == ''
) {
echo "Niste izpolnili vsa polja";
}
// ensure that passwords match
elseif($password1 != $password2) {
echo "Gesli se ne ujemata";
}
// validations passed
else {
echo "Registracija uspela";
}
Im currently working on this project for my assignment.i need to differentiate between user and admin on the login page. What changes should i made for the login page can differentiate between the user and admin ? these codes working just fine.
index.php
<?php
require_once 'php_action/db_connect.php';
session_start();
if(isset($_SESSION['userId'])) {
header('location: http://localhost/managementsystem/dashboard.php');
}
$errors = array();
if($_POST) {
$username = $_POST['username'];
$password = $_POST['password'];
if(empty($username) || empty($password)) {
if($username == "") {
$errors[] = "Username is required";
}
if($password == "") {
$errors[] = "Password is required";
}
} else {
$sql = "SELECT * FROM users WHERE username = '$username'";
$result = $connect->query($sql);
if($result->num_rows == 1) {
$password = md5($password);
// exists
$mainSql = "SELECT * FROM users WHERE username = '$username' AND password='$password'";
$mainResult = $connect->query($mainSql);
if($mainResult->num_rows == 1) {
$value = $mainResult->fetch_assoc();
$user_id = $value['user_id'];
//set session
$_SESSION['userId'] = $user_id;
header('location: http://localhost/managementsystem/dashboard.php');
} else {
$errors[] = "Incorrect Username or Password combination";
}
}else {
$errors[] = "Username does not exists";
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Log-in Page</title>
<!-- bootstrap -->
<link rel="stylesheet" type="text/css" href="assets/bootstrap/css/bootstrap.min.css">
<!-- bootstrap theme -->
<link rel="stylesheet" type="text/css" href="assets/bootstrap/css/bootstrap-theme.min.css">
<!-- font awesome -->
<link rel="stylesheet" type="text/css" href="assets/font-awesome/css/font-awesome.min.css">
<!-- custom css -->
<link rel="stylesheet" href="custom/css/custom.css">
<!-- jquery -->
<script type="text/javascript" src="assets/jquery/jquery.min.js"></script>
<!-- jquery ui -->
<link rel="stylesheet" href="assets/jquery-ui/jquery-ui.min.css">
<script src="assets/jquery-ui/jquery-ui.min.js"></script>
<!-- bootstrap js -->
<script src="assets/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row vertical">
<div class="col-md-5 col-md-offset-3">
<div class="panel panel-default">
<div class="panel-info">
<div class= "panel-heading text-center">
<h3 class= "panel-title">MH ALLIM Management System</h3>
</div>
<div class="panel-body">
<div class="messages">
<?php if($errors) {
foreach ($errors as $key => $value) {
echo '<div class="alert alert-warning" role="alert">
<i class="glyphicon glyphicon-exclamation-sign"></i>
'.$value.'</div>';
}
} ?>
</div>
<form class="form-horizontal" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST" id="loginForm">
<div class="form-group">
<label for="inputUser3" class="col-sm-2 control-label">Username</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="username" name="username" placeholder="Username">
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-2 control-label">Password</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="password" name="password" placeholder="Password">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default"> <i class="glyphicon glyphicon-log-in"></i>
Sign in</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Session.php
<?php
session_start();
require_once 'db_connect.php';
//echo $_SESSION['userId'];
if(!$_SESSION['userId']) {
header('location: http://localhost/managementsystem/index.php');
}
?>
should i modify the session so the normal user cannot access to the admin page ?
Thanks :)
You should have something that makes user and admin different. So, you can simply add a new column to your table with the name "role" (for example). If the user is a User, then the role will be "user". Same thing with any Admin, the role will be "admin".
And you can write the following code to your admin's page to prevent any login from unauthorized users. Use the same code with the user's page to prevent any login from any admin to the user's page "change this part to: $_SESSION['role'] != 'user')"
<?php
session_start();
require_once 'db_connect.php';
if( (empty($_SESSION['userId'])) || ($_SESSION['role'] != 'admin') ) {
echo "<script>window.open('index.php','_self');</script>";
}
else {
$userId = $_SESSION['userId'];
}
?>
Use if and else to separate it:
if(type="admin")
{
do somethg
}
else
{
do somethg
}
I have a problem logging users. When logs, session work, but when you click to another page, the session will disappear and does not work and when I put session_start to the main page and to login.php, I got error that session is already running. Some ideas? Thanks
Main Page.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" type="text/css" href="css.css">
<link rel="icon" href="favicon.ico">
<title>----</title>
</head>
<body>
<!-- HEADER _____________________________________________________________________________ -- >
<div id="whiteblock">
<div id="grayblock">
<div id="logo">
</div>
<h1>----</h1>
<h2>----</h2>
Registration
<?php
include "Login.php";
echo $_SESSION["LogiNick"];
?>
<div id="inputposunuti">
<form name="Log" id="Log" method="post">
<label for="Nick" class="inputtext">Nick:</label>
<input type="text" name="LogiNick" id="LogiNick" class="input"> <?php echo $EmptyNick; echo $Else; ?>
<label for="Pass" class="inputtext">Password:</label>
<input type="password" name="LogiPass" id="LogiPass" class="input"> <?php echo $EmptyPass; echo $Else; ?>
<input type="submit" name="LogIn" value="⇒">
</form>
</div>
</div>
<!-- HEADER _____________________________________________________________________________ -->
<!-- MENU _______________________________________________________________________________ -->
<div id="pruh">
<div id="search">
<form name="search" method="post">
<input type="text" name="hledat" id="sirka">
<input type="submit" name="subhledat" value="Search!" id="button">
</form>
</div>
<div id="menutext">
<p>Home</p>
<p>----</p>
<p>----</p>
<p>----</p>
<p>----</p>
<p>----</p>
</div>
</div>
<!-- MENU _______________________________________________________________________________ -->
<!-- CONTENT ____________________________________________________________________________ -->
<!-- CONTENT ____________________________________________________________________________ -->
<div id="teams"></div>
</div>
<p id="creator">Created by</p>
Login.php
<?php
session_start();
include_once "db.php";
global $db;
$Else = $EmptyNick = $EmptyPass = $EmptyNick = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$LogiNick = $_POST["LogiNick"];
$LogiPass = $_POST["LogiPass"];
if (empty($_POST["LogiNick"])) {
$EmptyNick = " - Nick";
}
if (empty($_POST["LogiPass"])) {
$EmptyPass = " - Password";
}
}
if(!empty($_POST["LogiNick"]) AND !empty($_POST["LogiPass"])){
$LogiPass = $_POST["LogiPass"];
$SHA = sha1($LogiPass);
$sql = "SELECT * FROM WEB_REGISTER WHERE Nick = :nick AND Heslo = :heslo";
$query = $db->prepare($sql);
$query->execute(array('nick' => $LogiNick, 'heslo' => $SHA));
$count = $query->rowCount();
if ($count > 0) {
$_SESSION["LogiNick"];
}
}
?>
You just set a session if you put a value into it.
$_SESSION["name"]=$value;
I'm trying to create a login system for my jQuery mobile app but it's not doing anything after the login button is clicked. Right now I'm not using a db connection.
index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<link href="jquery.mobile-1.1.0/jquery.mobile.theme-1.0.min.css" rel="stylesheet" type="text/css">
<link href="jquery.mobile-1.1.0/jquery.mobile.structure-1.1.0.min.css" rel="stylesheet" type="text/css">
<script src="jquery.mobile-1.1.0/jquery-1.7.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#loginform').submit(function(){
$('#output').html('Connecting...');
var postTo = 'http://www.hedonsoft.com/game/login.php';
$.post(postTo,{userLbl: $('[name=username]').val(), passwordLbl: $('[name=password]').val()}, function (data){
if(data.message){
$('#output').html(data.message);
}else{
$('#output').html("Could not connect");
}
}, 'json');
return false;
});
});
</script>
<script src="jquery.mobile-1.1.0/jquery.mobile-1.1.0.min.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="custom.css" />
</head>
<body>
<div data-role="page" id="mc_main">
<div data-role="header" id="header">
<h1>Main Menu</h1>
</div>
<div data-role="content">
<div data-role="collapsible" id="logindiv"><h2>Login</h2>
<form id="loginform" method="post">
<div data-role="fieldcontain">
<label for="user">Username:</label>
<input type="text" name="user" id="user" value="" />
</div>
<div data-role="fieldcontain">
<label for="pass">Password:</label>
<input name="pass" type="password" id="pass" value="">
</div>
<input type="submit" value="Login" data-icon="check" data-theme="a"/>
</form>
<div id="output"></div>
</div>
</div>
</body>
</html>
login.php
<?php
if(isset($_POST['username'] and isset($_POST['password'])) {
// do logic for logining in (usually query your db)
if ($_POST['username'] == 'test' and $_POST['password'] == 'test') {
$data['success'] = true;
$data['message'] = 'Login succesful';
} else {
$data['success'] = false;
$data['message'] = 'Login failed';
}
// return json
echo json_encode($data);
}
?>
I get 'Connecting...' in #output but that's it.
The login.php code has a syntax error on line 2. It should read:
if(isset($_POST['userLbl']) && isset($_POST['passwordLbl']))
Your input name for the user field is "user".
Change your javascript to look like this
$.post(postTo,{userLbl:$('[name=user]').val(), ...
Then your login.php should looke like this:
<?php
if(isset($_POST['userLbl'] and isset($_POST['passwordLbl'])) {
// do logic for logining in (usually query your db)
if ($_POST['userLbl'] == 'test' and $_POST['passwordLbl'] == 'test') {
$data['success'] = true;
$data['message'] = 'Login succesful';
} else {
$data['success'] = false;
$data['message'] = 'Login failed';
}
// return json
echo json_encode($data);
}
?>
Your server is returning an error 500. That's why it doesn't work!
You can check my fiddle if you want: http://jsfiddle.net/ooflorent/7cYae/