I am not worried about security, this is just a small project, which I am using only on my computer. I need to store a .txt file with data from a login form to the same location that the HTML file is. I don't think you can do it with javascript, but I don't know anything about PHP and I have tried many times to get this to work, but it isn't. Here is my code.
<form style="text-align: center;" action="./success.html" method="post">
<div class="form-group">
<label for="username">Username</label>
<input placeholder="Username" autocomplete="off" type="text" id="username" name="username"><br>
</div>
<div class="form-group">
<label for="password">Password</label>
<input placeholder="Password" autocomplete="off" type="password" id="password" name="password"><br><br>
</div>
<input id="button1" class="btn btn-success" type="submit" value="Sign Up">
<!-- When pressed, needs to store data in a data.txt file. -->
</form>
How would I be able to do this if I'm using this setup, and what would I need to change?
I'll just show you a quick example to get you started and create a JSON file with some data like:
{"username":"Lorem", "password":"ipsum"}
Rather than into .txt use a .json file. It's the today's most popular standard for storage and transmit of structured data.
Use AJAX to send a request and receive a response - without page refresh
Use json_encode the nifty PHP's file_put_content
Use JS's fetch ("POST") with the data being the FormData
Run the demo using php -S localhost:81 and open it in your browser:
save.php
<?php
if (
$_SERVER['REQUEST_METHOD'] === 'POST'
&& isset($_POST["username"])
&& isset($_POST["password"])
) {
$json = json_encode($_POST);
// Save JSON to file
file_put_contents("user.json", $json);
// Return some data back to the AJAX request.
echo $json;
// PS it's not wise to send passwords that way.
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" href="#!" type="image/x-icon">
<title>AJAX PHP - SAVE USER DATA </title>
</head>
<body>
<h1>User: <span data-username>Unknown</span></h1>
<form id="form-login" action="./save.php" method="post">
<div class="form-group">
<label>
<span>Username</span>
<input placeholder="Username" autocomplete="off" type="text" name="username">
</label>
</div>
<div class="form-group">
<label>
<span>Password</span>
<input placeholder="Password" autocomplete="off" type="password" name="password">
</label>
</div>
<input id="button1" class="btn btn-success" type="submit" value="Login">
</form>
<script>
const EL_formLogin = document.querySelector("#form-login");
EL_formLogin.addEventListener("submit", (ev) => {
ev.preventDefault(); // Stop default form submit - we'll use AJAX
fetch(EL_formLogin.action, {
method: 'POST',
body: new FormData(EL_formLogin),
}).then(res => res.json()).then(data => {
// Hide the form
EL_formLogin.hidden = true;
// Show the user name
document.querySelector("[data-username]").textContent = data.username;
});
});
</script>
</body>
</html>
DISCLAIMER!
Never store passwords in plaintext on your server files or database - and only send passwords over HTTPS.
Related
So I'm building a web application with the option to be admin and add data to a JSON file, which will be displayed onto another HTML page (index).
Now is my question: how to do it. How to get the data from the form, parse it, and put it in a JSON file. And can it be done without Node.js
This is my current JSON-file
{"accounts": [
{"email": "example-mail#mail.com", "password2":"Duck123"},
{"email": "example-mail2#mail.com", "password2":"Cow123"},
{"email" : "example-mail3#mail.com", "password2": "Chicken123"}
]}
This is my "Admin" page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="styles.css">
<title>ADMIN PAGE</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
<form id="adminform" action="#" method="post">
<div class="form-group">
<label for="emailadress">Email Address</label>
<input type="email" class="form-control" id="emailadress" required autocomplete="false">
</div>
<div class="form-group">
<label for="password2">Password</label>
<input type="password" class="form-control" id="password2" required>
<input type="button" value="Show Password" readonly onclick="passwordShow()" autocomplete="false">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
</body>
<script>
//show password on button click
function passwordShow() {
var x = document.getElementById("password2");
if (x.type === "password") {
x.type = "text";
} else {
x.type = "password";
}
}
</script>
</html>
If somebody knows how to do it, or has a tip, please let me know!
Direct writing to the filesystem can not be done from inside the Browser. However you have the possibility to create a "download" link, so that the user gets a notification that a file should be downloaded and can pick a location where to store that file.
Copied the following snippet from Stackoverflow: Download JSON object as a file from browser. You can use it to create exactly that download containing your json content.
function downloadObjectAsJson(exportObj, exportName){
var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(exportObj));
var downloadAnchorNode = document.createElement('a');
downloadAnchorNode.setAttribute("href", dataStr);
downloadAnchorNode.setAttribute("download", exportName + ".json");
document.body.appendChild(downloadAnchorNode); // required for firefox
downloadAnchorNode.click();
downloadAnchorNode.remove();
}
This is my first time with spring boot. So, I have a simple index.html page, i go to it just through localhost:8080. I have some console.log() in my js under the html and they dont log a single thing. The api does work though, i tried it in postman and there is no problem. But it seems that the js doesnt recognize anything of the html. This is what the console.log() prints in the console:
As you can see they are empty. See my structure and my code below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Page</title>
</head>
<body>
<form id="loginform">
<div class="form-group">
<label for="Username">Username</label>
<input name="username" class="form-control" type="text" placeholder="Enter username" required>
</div>
<div class="form-group">
<label for="Password">Password</label>
<input name="password" class="form-control" type="password" placeholder="Password" required>
</div>
<button id="login">Login</button>
</form>
<script>
function login() {
var formData = new FormData(document.querySelector("#loginform"));
var encData = new URLSearchParams(formData.entries());
console.log(formData);
console.log(encData);
console.log(document.querySelector("#loginform"));
fetch("/authenticate", {method: 'POST', body: encData})
.then(function (response) {
if (response.ok) {
window.location.href = "/lingogame.html";
return response.json();
} else {
alert("Invalid Username or password");
}
})
.then(myJson => window.sessionStorage.setItem("myJWT", myJson.JWT))
.catch(error => console.log(error));
}
var loginButton = document.querySelector("#login")
if (loginButton) {
loginButton.addEventListener("click", login);
}
</script>
</body>
</html>
The problem may result from CSRF support of Spring Security. Check CSRF support is enabled or disabled, by default it is enabled by Spring Security. If enabled you must be send csrf_token with "X-CSRF-TOKEN" header with csrfToken value, otherwise it is not required.
My window.location does not redirect the page to the required location. The same code with window.open works. The else statement also executes when the user name and password are incorrect. When the correct username and password is entered, it just refreshes the same page.
<div class="login" style="position:relative;top:200px;">
<form name="login" method="post">
<p align="middle">Please login to continue </p><p align="middle"><input type="text" name="login" placeholder="Username"></p>
<p align="middle"><input type="password" name="pwd" placeholder="Password"></p>
<p class="submit" align="middle"><input type="submit" onclick ="return check(this.form)" value="Login" name="commit"></p>
</form>
<script language="javascript">
function check(form) {
if(form.login.value == "admin" && form.pwd.value == "sysadmin") {
window.location('alumni.html');
}
else {
alert("Ten thousand thundering typhoons! What is the blasted password?");
}
}
</script>
<!--<script type='text/javascript' src='alumna.json'></script> -->
</div>
You can also try with
window.location = 'http://www.yoururl.com/alumni.html';
or directly
window.location = 'alumni.html';
There is a good question about redirect in javascript here: How do I redirect with Javascript?
[EDIT #1]
Although I think that is not the main problem. I believe you can not validate the way you are doing it. In the form there is an attribute called action as explained in http://www.w3schools.com/tags/att_form_action.asp
Then in the page you load, you validate the parameters and decide if its right or not, where you redirect to one page if its right, or to another if it's wrong.
Or you can also load the page and if validation is right, stay in the page and if it's wrong redirect to the login page.
That's one way to do it, probably there is another one better.
[EDIT #2]
What I would personally do is to process the form in a PHP page, it's much easier and simpler. Could be like:
in the HTML:
<div class="login" style="position:relative;top:200px;">
<form name="login" action="myPhpPage.php" method="post">
<p align="middle">Please login to continue </p>
<p align="middle"><input type="text" name="login" placeholder="Username"></p>
<p align="middle"><input type="password" name="pwd" placeholder="Password"></p>
<p class="submit" align="middle">
<input type="submit" onclick ="" value="Login" name="commit"></p>
</form>
<!--<script type='text/javascript' src='alumna.json'></script> -->
</div>
In the PHP page:
$name = $_POST['login']; // it's $_post because you are sending the form with method = post
$pass = $_POST['pwd'];
if($name == "admin" && $pass == "sysadmin"){
//go to one page or stay here
} else{
// redirect to another page
}
window.location is a read only property:
The Window.location read-only property returns a Location object with information about the current location of the document.
MDN on window.location
try this: window.location.replace("http://stackoverflow.com");
Here's a working code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title> Login Redirection Test</title>
<script>
function validateForm() {
var un = document.forms["login"]["user"].value;
var pw = document.forms["login"]["pwd"].value;
if (un == "admin" && pw=="sysadmin") {
window.location.assign="https://stackoverflow.com";
return false;
}else {
alert("Ten thousand thundering typhoons! What is the blasted password?");
}
}
</script>
</head>
<body>
<div class="login" style="position:relative;top:200px;">
<form name="login" onsubmit="return validateForm()" method="post">
<p align="middle">Please login to continue </p><p align="middle"><input type="text" name="user" placeholder="Username"></p>
<p align="middle"><input type="password" name="pwd" placeholder="Password"></p>
<p class="submit" align="middle"><input type="submit" onclick ="return check(this.form)" value="Login" name="commit"></p>
</form>
<!--<script type='text/javascript' src='alumna.json'></script> -->
</div>
</body>
</html>
Window.location is not a function, it is a property that is just read. However,
window.location.assign
might work better.
Hi guys i have a following code in which i am trying to redirect to another ,i am using javascript html to achieve this,and i am new to html, javascript and php. It is showing test.phpbut as i click on button it does not redirect to logout_success.php.
<!DOCTYPE HTML>
<html>
<head>
<title>Sign-In</title> <link rel="stylesheet" type="text/css" href="style-sign.css">
</head>
<body id="body-color">
<div id="Sign-In">
<fieldset style="width:30%">
<legend>LOG-IN HERE</legend>
<form method="POST" action="connectivity.php">
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" onclick="document.location.href='http://localhost:8080/PortalWork/logout_success.php'">
</form>
</fieldset>
</div>
</body>
</html>
There are two ways.
(1) Submit form with AJAX, and redirect with window.location.href
$("#form1").submit(function(e){
e.preventDefault();
$.ajax({
url:'connectivity.php',
method:'POST',
success:function(rs){
if( rs == "success" )
window.location.href("logout_success.php");
},
error:function(){
alert("Error");
}
});
return false;
});
http://jsfiddle.net/hxm49uk2/
(2) Submit to server, and redirect with header("Location:page.php");
connectivity.php
header("Location:logout_success.php");
You can do it in JS like this:
<button name="button" onclick="window.location.href='http://www.google.com'">Go</button>
Instead of http://www.google.com use your desired url.
Just include the following code in connectivity.php
header("Location:logout_success.php"); // give the correct path of logout_success.php
And take off onclick from form submit button
<input id="button" type="submit" name="submit" value="Log-In">
I'm working on phonegap, basically its like making mobileapps crossplatform by using HTML, JS and CSS. On the device i currently have the JS and the HTML (form) in same document.
What I'm trying to do is to pass email and password to my server, and then process it there through a login. I've tested the login script on the server and it works with hardcoded data. So I'm guessing somewhere when sending the data from the device its failing.. I'm fairly new to JS too.
I tried to hardcode the data in the AJAX but it doesnt seem to work. Preferebly I would like to use something like var pdata = $('#form').serialize(); or something else if its better.
Any ideas?
EDIT: Forgot to say that the PHP on the server auto submits by using JS when $_POST is set (isset)
The form
<form id="form" onsubmit="dologin()">
<div class="form-group">
<label for="email">Epost</label>
<input type="email" class="form-control" name="email" value="" placeholder="Epost">
</div>
<div class="form-group">
<label for="password">Passord</label>
<input type="password" class="form-control" name="password" value="" placeholder="Passord">
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="remember_me">
Husk meg
</label>
</div>
<button type="submit" class="btn btn-primary">Logg inn</button>
</form>
The javascript
<script>
function dologin() {
//var pdata = $('#form').serialize();
//alert(pdata);
$.ajax({
type: 'POST',
data: {email:"test#test.no",password:"test"},
url: 'LINK',
success: function(data) {
alert(data);
},
error: function() {
alert("error");
}
});
return false;
};
</script>
The PHP
<form id="form" method="post">
<!-- {{ Form::label('email', 'Email Address') }} -->
<div class="form-group">
<input type="text" name="email" value="<?php if(isset($_POST["email"])) echo $_POST['email'];?>">
</div>
<div class="form-group">
<!-- {{ Form::label('password', 'Password') }} -->
<input type="text" name="password" value="<?php if(isset($_POST["password"])) echo $_POST['password'];?>">
</div>
</form>
Are you able to hit your server via through phonegap?
If no then please check your config.xml for white list urls - change access control property to
access origin = "*"
Hopeful you will be able to hit your server with data.
You can use weinre to debug your app. That way you will be able to see if the request was placed from the app or not.
http://people.apache.org/~pmuellr/weinre/docs/latest/Home.html