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
Related
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();
});
I'm trying to destroy/reset my session so it cleans the Logs div I created when I press on the Reset Button in my Form. I have assigned a method to my button (btnReset) from a .js file that clears the entire page. Now I just want to make so that it just clears the Logs div where all my calculations are stored at. I have no idea what to do.
Any help would be super much appreciated. SESSIONS is still very new to me so I'm trying my best to understand it. If anyone can explain to me how to properly clear the Logs div after the Reset button has pressed to destroy/reset my session, that would be very much appreciated!
Index.php
<?php
session_start();
if (!isset($_SESSION['results'])) {
$_SESSION["results"] = [];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Meta Tags -->
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Calculator++ with PHP">
<!-- Title -->
<title>Calculator ++ | Calculator</title>
<!-- Favicon -->
<link rel="icon" type="image/png" sizes="16x16" href="Images/favicon-16x16.png">
<link rel="icon" type="image/png" sizes="32x32" href="Images/favicon-32x32.png">
<!-- Stylesheets -->
<link rel="stylesheet" type="text/css" href="CSS/Style.css">
<!-- PHP Files -->
<?php include 'PHP/Calculation.php';?>
</head>
<body>
<!-- Selection for Calculator & Converter -->
<div class="selection">
<div class="titleSelect">Options</div>
<a class="btn-selection" href="Index.php">Calculator</a>
<a class="btn-selection" href="Converter.php">Converter</a>
</div>
<!-- Calculator Container -->
<div class="container">
<div class="result">
<!-- Prints the result -->
<div class="result"><?php echo $Result; ?></div>
</div>
<div class="calculator">
<form action="Index.php" method="POST">
<ul>
<!-- First number -->
<li>
<label for="numberOne"><strong>Number one:</strong></label>
<input class="inputNumbers" type="number" name="numberOne" placeholder="Enter a number">
</li>
<!-- Operation -->
<li>
<label for="operation"><strong>Operation:</strong></label>
<select class="inputNumbers" name="operation" id="operator-list">
<option value="+">+</option>
<option value="-">-</option>
<option value="x">x</option>
<option value="/">/</option>
<option value="sqrt">^</option>
<option value="pow">√</option>
</select>
</li>
<!-- Second number -->
<li id="second-input">
<label for="numberTwo"><strong>Number two:</strong></label>
<input class="inputNumbers" type="number" name="numberTwo" placeholder="Enter a number">
</li>
<!-- Decimal Slider -->
<li>
<label><strong>Decimal: </strong><span id="value_slider"></span></label>
<input type="range" name="slidebar" min="0" max="10" value="0" id="slider" class="slider_style input">
</li>
<!-- Calculate & Reset button -->
<li>
<input class="btn-calculate" type="submit" name="btnCalculate" value="Calculate">
<button class="btn-reset" type="reset" name="resetForm" onclick="btnReset();" value="resetButton">Reset</button>
</li>
</ul>
</form>
</div>
<!-- Logs -->
<div class="logs-container">
<div class="logs-title">Logs</div>
<div class="logs">
<?php echo implode("<br>",$_SESSION["results"]); ?>
</div>
</div>
</div>
<!-- JavaScript -->
<script type="text/javascript" src="JS/HideSecondInput.js"></script>
<script type="text/javascript" src="JS/Slider.js"></script>
<script type="text/javascript" src="JS/Reset.js"></script>
</body>
</html>
Calculation.php
<?php
$Result = 0;
if (isset ($_POST['btnCalculate']) ) {
$numberOne = $_POST['numberOne'];
$operation = $_POST['operation'];
$numberTwo = $_POST['numberTwo'];
if ($operation == '+') {
$Result = ((int)$numberOne + (int)$numberTwo);
$_SESSION["results"][]="$numberOne + $numberTwo = $Result";
}
else if ($operation == '-') {
$Result = ((int)$numberOne - (int)$numberTwo);
$_SESSION["results"][]="$numberOne - $numberTwo = $Result";
}
else if ($operation == 'x') {
$Result = ((int)$numberOne * (int)$numberTwo);
$_SESSION["results"][]="$numberOne * $numberTwo = $Result";
}
else if ($operation == '/') {
if ($numberOne and $numberTwo > 0)
{
$Result = $numberOne / $numberTwo;
$_SESSION["results"][]="$numberOne / $numberTwo = $Result";
} else {
echo "<script>alert('Cannot divide by 0');</script>";
}
}
else if ($operation == 'sqrt') {
$Result = sqrt($numberOne);
$_SESSION["results"][]="sqrt($numberOne) = $Result";
}
else if ($operation == 'pow') {
if ($numberOne and $numberTwo > 0)
{
$Result = pow($numberOne, $numberTwo);
$_SESSION["results"][]="pow($numberOne, $numberTwo) = $Result";
} else {
echo "<script>alert('Please enter a number in both fields');</script>";
}
}
else $Result = 'Unknown';
}
?>
Reset.js
//Resets the entire page when reset button is pressed
function btnReset() {
const xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", false);
xmlhttp.send();
window.parent.location = window.parent.location.href;
}
you basically need to adjust your code in the following way:
btnReset should send specific flag for session to be destoryed
btnReset should wait for the request to finish, then do the redirect.
on PHP, you should check for the flag, and if found, delete the session.
function btnReset(event) {
const xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", '/index.php?reset=true', true);
xmlhttp.onreadystatechange = function() { // Call a function when the state changes.
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
window.parent.location = window.parent.location.href;
}
}
xmlhttp.send();
}
and In PHP (calucations.php):
if(#$_GET['reset'] == true) {
$_SESSION["results"] = [];
session_destroy();
}
of course, this is simple way to do it, you should consider using jQuery https://jquery.com/ which would help you with the AJAX request, and also instead of doing a redirect, you can simple delete the content of the div containing the logs.
Note some typos in your code, file was called "Index.php" it should be case sensitive, so always call it: index.php
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.
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);
}
I'm making an instant chat service using PHP and Async javascript. Messages are taken from a database and placed into a text area. The problem is that when messages require the textarea to scroll the setInterval() function used to check and grab new messages forces the text area back to the top of its scrolling height.
I've seen a few solutions and none have worked so far. I tried setting the scrollTop to equal the scrollHeight, but to no avail.
Here's some code:
window.onload = function()
{
if(getUrlVars()['to'] != null)
setInterval(GetMessages, 1000);
}
function ToServer(cmd, data)
{
xmlObj = new XMLHttpRequest();
xmlObj.open('POST','handler.php',true);
xmlObj.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlObj.send(cmd + data);
xmlObj.onreadystatechange = function()
{
if(xmlObj.readyState == 4 && xmlObj.status == 200)
{
if(cmd == 'cmd=push')
{
document.getElementById('pushResponse').innerHTML = xmlObj.responseText;
}
if(cmd == 'cmd=pop')
{
document.getElementById('messages').value += xmlObj.responseText;
}
}
}
}
function GetMessages()
{
// Grab account hash from auth cookie
aHash = readCookie('privateChat');
to = getUrlVars()['to'];
ToServer('cmd=pop','&account=' + aHash + '&to=' + to);
textArea = document.getElementById('messages');
textArea.scrollTop = textArea.scrollHeight;
}
And here's the HTML:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Private Chat</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div>
<h2>Conversation with {%RECIPIENT%}</h2>
<div id="fieldContainer">
<textarea col="10" rows="5" name="messageBox" id="messages"></textarea>
</div>
</div>
<div>
<legend>Message</legend>
<div id="fieldContainer">
<input type="text" id="msgBox">
</div>
</div>
<div>
<input type="button" name="fSend" value="Send message" onClick="SendMessage();">
</div>
<div id="pushResponse">Response</div>
<script src="Chat.js"></script>
</body>
</html>
Thanks!