Mobile authentification with php/html/jquery - php

Hello I'm trying to do simple authentification application on android, I use dreamweaver as editor. Well here is the code, please can you tell why I'm not redirected to login.php after a success authentification.
index.html
<html><head>
<meta charset="utf-8">
<title>Guide touristique</title>
<link href="jquery.mobile.theme-1.0.min.css" rel="stylesheet" type="text/css"/>
<link href="jquery.mobile.structure-1.0.min.css" rel="stylesheet" type="text/css"/>
<script src="jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="jquery.mobile-1.0.min.js" type="text/javascript"></script>
<script language="javascript">
$(document).ready(function() {
$("#loginform").submit(function() {
$.post('auth.php', $(this).serialize(), function(data) {
$("#errorm").html(data); // semicolon missing in your code
}); // round bracket and semicolon missing in your code
}); // round bracket missing in your code
return false;
});
</script>
</head>
<body>
<div data-role="page" id="page2">
<div data-theme="a" data-role="header">
</div>
<div data-role="content" style="padding: 15px">
<div style="text-align:center">
</div>
<form id="loginform" method='post'>
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<label for="textinput2" style="text-align:right">
Email:
</label>
<input id="textinput2" name="login" value="" type="text"/>
</fieldset>
</div>
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<label for="textinput3" style="text-align:right">
Password: </label>
<input id="textinput3" name="password" value="" type="password"/>
</fieldset>
</div>
<h3 id="errorm"> <?php if (isset($_GET['msg'])){
echo "Invalid username or password";
}
?></h3>
<input type="submit" name="submit" id="submit" data-inline="true" data- icon="arrow-l" data-iconpos="left" value="login"/>
</form>
</body>
</html>
auth.php
<?php
//Sanitize the POST values
$login = $_POST['login'];
$password = $_POST['password'];
$aqry="SELECT * FROM user WHERE utilisateur='".$login."' AND pswd='".$_POST['password']."'";
$conn=mysql_query($eqry);
if( $conn ){
//Check whether the query was successful or not
if(mysql_num_rows($conn) == 1) {
//Login Successful
/* $member = mysql_fetch_assoc($conn);
$_SESSION['MEMBER_ID'] = $member['id'];
$_SESSION['NAME'] = $member['utilisateur'];
*/
header("location: login.php");
exit();
}
else {
//Login failed
header("Location: mobile/mlogin.php?msg=invalid%20name%20or%20password");
exit();
}
?>
login.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>login</title>
</head>
<body>
You're logging on
</body>
</html>

You are doing the login via an ajax request with $.post(), which means that the redirect you are sending is being captured by the ajax request. If you look in FireBug or something similar, you should see that the result of the ajax call is actually login.php.
I'd recommend having auth.php always return a json response (see http://php.net/manual/en/function.json-encode.php) something like {"result":"success", "redirect":"login.php"} or {"result":"error", "message":"abcd"}
In your ajax response handler:
if (data.result == "success") {
window.location = data.redirect;
} else {
$("#errorm").html(data.message);
}

Related

html value doesn't appear as visible with jQuery in php form

Just started working with php and little bit struggling with jQuery. Went through documentation and in my opinion everything should be working fine, however no. The hidden value does not appear visible after entering the wrong data into form. In css I assigned to #warning display:none
index.php
<?php require "../src/models/Database.php"; ?>
<?php include_once "../src/controllers/DatabaseController.php"; ?>
<?php session_start(); ?>
<?php include "../src/includes/header.php"; ?>
<?php
if (isset($_POST["submit"])) {
$username = $_POST["username"];
$password = $_POST["password"];
$dbController = new DatabaseController();
$dbController->loginUser($username, $password);
}
?>
<div class="container main">
<h1 class="text-center">Web</h1>
<p class="text-center" id="warning">Incorrect username or password</p>
<div class="row login-page">
<form class="form" method="POST">
<input class="form-control" type="text" name="username" placeholder="Username" required>
<input class="form-control" type="password" name="password" placeholder="Password" required>
<input class="btn btn-success" type="submit" name="submit" value="Login">
</form>
</div>
</div>
<?php include "../src/includes/footer.php"; ?>
header.php
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Bootstrap starts -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<!-- Bootstrap ends -->
<!-- Css starts -->
<link rel="stylesheet" href="../src/styles/css/main.css">
<!-- Css ends -->
<!-- Jquery starts -->
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<!-- Jquery ends -->
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title id="title"></title>
</head>
<body>
databasecontroller.php
<?php
class DatabaseController extends Database
{
public function loginUser($username, $password)
{
$connection = $this->connection;
$escapedUsername = mysqli_real_escape_string($connection, $username);
$escapedPassword = mysqli_real_escape_string($connection, $password);
$query = "SELECT * FROM users WHERE username = '$escapedUsername'";
$result = $this->findUser($query, $escapedPassword);
if ($result) {
// $_SESSION["authenticated"] = true;
echo "Logged in";
} else { ?>
<script>
$("#warning").show();
</script>
<?php
}
}
}
composer.json
{
"require": {
"components/jquery": "^3.5"
}
}
You are including the jQuery script before the html is finished.
Therefore, there is no #warning on the page, yet. Nothing is shown.
You should either include your script after the <p class="text-center" id="warning"> or you can tell jQuery to wait until the document is ready before applying the show():
$( document ).ready(function() {
$("#warning").show();
});

Angular $http.post() returning html code

I am trying to do a post request using angular and getting the response as the html code of index.html. I am using zurb's foundation for apps.
<!doctype html>
<html lang="en" ng-app="application">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Foundation for Apps</title>
<link href="./assets/css/app.css" rel="stylesheet" type="text/css">
<script src="./assets/js/foundation.js"></script>
<script src="./assets/js/templates.js"></script>
<script src="./assets/js/routes.js"></script>
<script src="./assets/js/app.js"></script>
</head>
<body>
<div class="grid-frame vertical">
<div class="grid-content shrink" style="padding: 0;">
<ul class="primary condense menu-bar">
<li><a><strong>opt1</strong></a></li>
<li><a ui-sref="pros"><strong>opt2</strong></a></li>
</ul>
</div>
<div ui-view class="grid-content" >
</div>
</div>
</div>
</body>
</html>
home.html is by set as root so it will be displaying a login form
<form ng-controller="LoginController as login" ng-submit="login.loginProcess()">
<div class="grid-block">
<div class="grid-content">
<input type="text" name="username" ng-model="login.user.username">
</div>
<div class="grid-content">
<input type="password" name="password" ng-model="login.user.password">
</div>
<div class="grid-content">
<input type="submit" value="submit">
</div>
</div>
</form>
This is my app.js file
(function() {
'use strict';
var application = angular.module('application', [
'ui.router',
'ngAnimate',
//foundation
'foundation',
'foundation.dynamicRouting',
'foundation.dynamicRouting.animations'
])
.config(config)
.run(run)
;
config.$inject = ['$urlRouterProvider', '$locationProvider'];
function config($urlProvider, $locationProvider) {
$urlProvider.otherwise('/');
$locationProvider.html5Mode({
enabled:false,
requireBase: false
});
$locationProvider.hashPrefix('!');
}
function run() {
FastClick.attach(document.body);
};
application.controller('LoginController',['$scope','$http',function($scope,$http){
this.user = {};
this.loginProcess = function(){
console.log(JSON.stringify(this.user));
var postData = JSON.stringify(this.user);
var config = {method: 'POST', url: '/login.php', data:postData};
$http(config)
.success(function(data, status, headers, config) {
console.log(data);
})
.error(function(data, status, headers, config) {
$scope.errorMsg = 'Unable to submit form';
});
};
}]);
})();
Now as soon as i submit the form I am able to fetch the data properly from the form but it is not being posted properly since the html code of index.html is being displayed in the console when the success function runs.Please suggest a solution so that i will be able to fetch the data from the php file.
<?php
echo $_REQUEST['username'];
?>
and its not working even if I use
file_get_contents("php://input");
In login.php write your php code before any html code starts and add a die() before any html code starts.
login.php
<?php
/*
php code to login
*/
die();
?>
<html>
....
</html>

jQuery & PHP code not connecting to mySql DB

For the life of me I can't figure out why the following code is not working. I'm quite inexperienced so any assistance appreciated.
I want to get a simple connection working where an ajax call will return a username from a mySQL DB (this is a precursor to a much larger project). My HTML file is the following:
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="jquery/test-theme.min.css"/>
<link href="jquery/jquery.mobile.icons.min.css" rel="stylesheet" />
<link href="jquery/jquery.mobile.structure-1.4.5.min.css" rel="stylesheet" />
<link href="jquery/app.css" rel="stylesheet" />
<script src="jquery/jquery-2.1.4.min.js"></script>
<script src="jquery/jquery.mobile-1.4.5.min.js"></script>
<script> function login(){
$(document).ready(function(){
var user = $("#username")[0].value;
var email = $("#email")[0].value;
$.ajax({
type: "GET",
url: "http://localhost:8888/test/connection.php",
data: "username="+user+"&email="+email,
success: function(result){
if(result){
$("#message")[0].value = "Success" +result;
}
else{
$("#message")[0].value = "Fail :(";
}
},
error: function(result){
$("#message")[0].value = "Ajax error!"+result;
}
});
});
}
</script>
</head>
<body>
<div data-role="page">
<div data-role="header" data-theme="c">
<h1>Sign Up!</h1>
</div><!-- /header -->
<div role="main" class="ui-content">
<h3>Sign Up</h3>
<label for="txt-first-name">Username</label>
<input type="text" name="txt-first-name" id="username" value="" onkeyup="login()">
<label for="txt-email">Email Address</label>
<input type="text" name="txt-email" id="email" value="" onkeyup="login()">
<input type="text" id="message"></input>
<button id="submit" onclick="login()"> Submit</button>
<div data-role="popup" id="dlg-sign-up-sent" data-dismissible="false" style="max-width:400px;">
</div>
</div><!-- /content -->
</div>
</body>
</html>
And my PHP:
<?php
$user = $_REQUEST['username'];
$email = $_REQUEST['email'];
mysql_connect("localhost:8889","root","root") or die(mysql_error());
mysql_select_db("TEST") or die(mysql_error());
$result = mysql_query("SELECT username, email FROM login WHERE username ='$user'");
while($row = mysql_fetch_array($result)){
if($user = $row["username"]){
echo $row["id"];
}
else{
echo "failed getting user"
}
}
?>
I have a DB called TEST running via MAMP with some entries in the login table for username and email. I just want to get the connection running properly but I'm stumped.

Phonegap ajax and php

I am new to jquery and phonegap and i am un able to find an answer to my question anywhere.
This is my index.html
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Auth Demo 2</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/latest/jquery.mobile.min.css" />
<script type="text/javascript" charset="utf-8" src="cordova-2.2.0.js"></script>
<script src="jquery.mobile/jquery-1.7.2.min.js"></script>
<script src="jquery.mobile/jquery.mobile-1.1.0.min.js"></script>
<script src="main.js"></script>
</head>
<body onload="init()">
<div id="launcherPage" data-role="page">
<!-- I'm just here waiting for deviceReady -->
</div>
<div id="loginPage" data-role="page">
<div data-role="header">
<h1>Auth Demo</h1>
</div>
<div data-role="content">
<form id="loginForm">
<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 data-role="footer">
<h4>© Camden Enterprises</h4>
</div>
</div>
</body>
</html>
And my Js.
function init() {
document.addEventListener("deviceready", deviceReady, true);
delete init;
}
function checkPreAuth() {
console.log("checkPreAuth");
var form = $("#loginForm");
if(window.localStorage["username"] != undefined && window.localStorage["password"] != undefined) {
$("#username", form).val(window.localStorage["username"]);
$("#password", form).val(window.localStorage["password"]);
handleLogin();
}
}
function handleLogin(){
var form = $("#loginForm");
var u = $("#username", form).val();
var p = $("#password", form).val();
//remove all the class add the messagebox classes and start fading
if(u != '' && p!= '') {
$.post("http://www.myaddress.com/loginlogin.php",{ user_name:$('#username', form).val(),password:$('#password', form).val(),rand:Math.random() } ,function(data)
{
if(data=='yes') //if correct login detail
{
//store
window.localStorage["username"] = u;
window.localStorage["password"] = p;
// $.mobile.changePage("some.html");
$.mobile.changePage( "some.html", { transition: "slideup"} );
}
else
{
navigator.notification.alert("Your login failed", function() {});
}
});
} else {
//Thanks Igor!
navigator.notification.alert("You must enter a username and password", function() {});
$("#submitButton").removeAttr("disabled");
}
return false;//not to post the form physically
}
function deviceReady() {
console.log("deviceReady");
$("#loginPage").on("pageinit",function() {
console.log("pageinit run");
$("#loginForm").on("submit",handleLogin);
checkPreAuth();
});
$.mobile.changePage("#loginPage");
}
Non of this is my own work but from here
http://www.raymondcamden.com/index.cfm/2011/11/10/Example-of-serverbased-login-with-PhoneGap
I changed the the example to work with php. This is very simple and only for testing purposes
php here
<?//get the posted values
require_once("backend/functions.php");
dbconn(true);
$username = $_POST['user_name'];
if ($username=='Steven'){
echo "yes";
}else{
echo "no";
}
?>
Now this all works and when the conditions are met the page some.html opens.
Now my question is .
How would i send the username of the logged in person to the page some.html?
once confirmed from the php file.
You should be able to access
window.localStorage["username"]
on your some.html page

How to hide elements with Jquery if PHP variable is set

I've got this piece of script, and I'm trying to hide two divs (#black and #yname) if a certain variable or session is set in PHP, so is there a simple way to do so?
Here's my code:
input.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<style type="text/css">
#import "stil.css";
</style>
<title>Untitled Document</title>
<script type="text/javascript" src="jq.js"></script>
<script type="text/javascript" src="jquery-ui-1.8.13.custom.min.js"></script>
<script type="text/javascript" src="scripts.js"></script>
<script type="text/javascript" src="postme.js"></script>
</head>
<body>
<div id="wrap">
<div id="chat">
<div id="main">
</div>
<div id="input">
<form name="form"action="test.php" method="post">
<input type="text" name="tekst" id="msg" size="72" />
<input type="submit" name="dugme" value="posalji" id="dugme" />
</form>
</div>
</div>
</div>
<div id="black">
</div>
<div id="yname">
<form name="yname">
<input type="text" name="tekst2" />
<input type="button" name="dugme2" value="Enter" onclick="send()"/>
</div>
</body>
</html>
postme.js
function send(){
$.post('sesion.php',{name:yname.tekst2.value},function(val){
}
});
}
sesion.php
<?php
session_start();
$data=$_POST['name'];
$_SESSION['name']=$data;
$sesion_n=$_SESSION['name'];
echo $sesion_n;
?>
So basically, what I want to do is to check if $sesion_n variable is set, and if it's set, I want my send() function to hide divs #black and #yname.
In addition, is there a way to use val value with jquery somehow for example to alert it or to assign that value to a javascript variable?
function send(){
$.post('sesion.php',{name:yname.tekst2.value},function(val){
if(val) {
$('#black').hide();
$('#yname').hide();
}
}
});
}
well i didnt get your question completely but you can use hide() method to hide any div in jquery...

Categories