Javascript - cannot get login script to only accept set password - javascript

I am trying to make a basic login screen using Javascript, in which I don't have much experience. I managed to get this much, but for some reason, whenever I enter text into the input box it will redirect me, no matter whether it is the correct password or not.
Also, a second question, to determine whether or not a user has logged in (to redirect them to the login page), would I have to use something other than JS, such as PHP?
Code:
<!doctype html>
<html>
<head>
<title>Login</title>
<script type="text/javascript">
function login()
{
if (password = "cat")
{
location.assign("home.html");
}
}
</script>
</head>
<body>
Password: <input type = "password" name = "password">
<input type = "button" value = "Login" onclick = "login()">
</body>
</html>

currently you are using if(password = "cat") which is actually an assignment operator not used for comparison. If you don't know the type of data to be compared use == otherwise you can use ===.
In otherword
== is used to compare the values only.
=== is used to compare the values as well as type.
Check like this
if(password === "cat")
And for your another query if you want to make a web app or something. You should use server side interaction using PHP or WPF or any other like JSON etc.

This question has been asked by many before. The code needs to use an Ajax request to the server.
Also , you do need a server side language to do the validation . Something like below, example is using Jquery library
HTML
<body>
<?php session_start(); ?>
<div id="profile">
<?php if(isset($_SESSION['user_name'])){
?>
<a href='logout.php' id='logout'>Logout</a>
<?php }else {?>
<a id="login_a" href="#">login</a>
<?php } ?>
</div>
<div id="login_form">
<div class="err" id="add_err"></div>
<form action="login.php">
<label>User Name:</label>
<input type="text" id="user_name" name="user_name" />
<label>Password:</label>
<input type="password" id="password" name="password" />
<label></label><br/>
<input type="submit" id="login" value="Login" />
<input type="button" id="cancel_hide" value="Cancel" />
</form>
</div>
<div id="shadow" class="popup"></div>
</body>
Javascript
<script type="text/javascript">
$(document).ready(function(){
$("#login_a").click(function(){
$("#shadow").fadeIn("normal");
$("#login_form").fadeIn("normal");
$("#user_name").focus();
});
$("#cancel_hide").click(function(){
$("#login_form").fadeOut("normal");
$("#shadow").fadeOut();
});
$("#login").click(function(){
username=$("#user_name").val();
password=$("#password").val();
$.ajax({
type: "POST",
url: "login.php",
data: "name="+username+"&pwd="+password,
success: function(html){
if(html=='true')
{
$("#login_form").fadeOut("normal");
$("#shadow").fadeOut();
$("#profile").html("<a href='logout.php' id='logout'>Logout</a>");
}
else
{
$("#add_err").html("Wrong username or password");
}
},
beforeSend:function()
{
$("#add_err").html("Loading...")
}
});
return false;
});
});
</script>
PHP code
<?php
session_start();
$username = $_POST['name'];
$password = md5($_POST['pwd']);
$mysqli=mysqli_connect('localhost','username','password','database');
$query = "SELECT * FROM user WHERE username='$username' AND password='$password'";
$result = mysqli_query($mysqli,$query)or die(mysqli_error());
$num_row = mysqli_num_rows($result);
$row=mysqli_fetch_array($result);
if( $num_row >=1 ) {
echo 'true';
$_SESSION['user_name']=$row['username'];
}
else{
echo 'false';
}
?>

This is really the wrong way to implement login. Any password checking has to happen on the server, because otherwise the password will be visible on the client, and it will be trivial for users to see the required password. Furthermore, please, please, please, please do not create yet another username/password login... this is what OAuth2 is intended to solve; let the identity experts handle login, and simply delegate to another identity provider.
That being said, the error in your code is that you use a single equals sign ("=") which performs assignment, whereas you really intend to use the double equals ("==") or triple equals ("===") for comparison.

Related

Run a JavaScript function from a php if statement

I would like to create a php IF statement so If it receives the key "test" by POST, <h2> hello </ h2> should be output, otherwise <span> error </ span>
How can I make that?
<div id="rre">
<h2 class="desktop">Hamburg,a major port city in northern Germany.</h2>
<h2 class="mobil">Berlin,is the capital and the largest city of Germany.</h2>
</div>
<form action="viereck.html" method="POST">
<input type="text" name="check"?>
<input type="button" value="Klick" onclick="klick();" />
</form>
<script type="text/javascript">
function klick() {
jQuery('#rre').html('<h1>Hallo</h1>');
}
</script>
The response that you return needs to be inside script tags like:
echo '<script type="text/javascript">alert();</script>';
Why you don't do that with jquery: Try smth like this
<script type="text/javascript">
function klick() {
if($("#text").val() == 'test'){
jQuery('#rre').html("<h1>Hello there!</h1>");
}else{
jQuery('#rre').html("Error");
}
}
</script>
Html
<div id="rre">
<h2 class="desktop">Hamburg,a major port city in northern Germany.</h2>
<h2 class="mobil">Berlin,is the capital and the largest city of Germany.</h2>
</div>
<form action="viereck.html" method="POST">
<input type="text" name="check"? id="text">
<input type="button" value="Klick" onclick="klick();" />
</form>
JSFIDDLE
If the page you're posting to is viereck.html, you're going to be unable to use PHP on it.
If you can change the file to viereck.php, you can POST to it like you're doing, with action="viereck.php" method="POST" Then, at the top of your page, check for POST values in PHP like:
<?php
if(isset($_POST['check'])){
$check = '<span>error</span>';
if($_POST['check'] == 'test'){
$check = '<h1>Hallo</h1>';
}
}
?>
And if your jQuery is on the same page, you can insert the PHP like:
<script type="text/javascript">
function klick() {
jQuery('#rre').html(<?= $check; ?>);
}
</script>
Doing it this way though can lead to some serious headaches as your project grows, I wouldn't recommend it. Why not look into using AJAX? You can submit a form and return a message indicating success or failure, as well as why. You can then create your HTML in jQuery instead of a PHP string like:
// On form submit
$.ajax({
url: "viereck.php",
type: 'POST',
success: function(result){
var msg = $('<h1>').text('Hallo');
$('#rre').html(msg);
},
error: function(result){
var msg = $('<span>').text('Error');
$('#rre').html(msg);
}
});

Get value from input text in php without pressing Enter

Hay I'm new to php and I have made php code like this :
<?php
session_start();
echo 'Hellow Hisoka';
?>
<form name="form" method="post">
<div class="col-sm-3">
<label class:>Nama :</label>
</div>
<div class="col-sm-9">
<input type="text" name="nama_tamu" id='nama_tamu' class="form-control" placeholder="Nama Lengkap">
<?php
$myValue = $_POST['nama_tamu'];
?>
</div>
<br/><br/>
<?php
echo $myValue;
?>
</form>
When I want to show the echo message, I need to hit enter on my keyboard first in order to get the value of $_POST['nama_tamu'];. My question is can I get the value of nama_tamu input without pressing enter, or maybe without using POST or GET and then assign it to $myvalue?
You will need to use Javascript. You can use the Jquery events :
<script>
$( "#nama_tamu" ).keyup(function() {
alert( $this.val() );// alerting the value of the input field
});
</script>
Web development is all about communication. In this case, communication between two (2) parties, over the HTTP protocol:
The Server - This party is responsible for serving pages.
The Client - This party requests pages from the Server, and displays them to the user. In most cases, the client is a web browser.
Each side's programming, refers to code which runs at the specific machine, the server's or the client's.
You cannot get values without submitting for the user has not entered any yet. PHP is a server side language. To get values before submit and do certain actions with them you will need javascript (a client side programming language).
The simplest method to get a value is using the getElementById().
var something = document.getElementById('someid');
<input type="text" name="something" id="someid">
You can also use jQuery:
var something = $('#someid').val();
Conclusion
The simple answer to your question is: This is not possible.
Why not? I hear you asking. Because PHP doesn't know the values of your form before you send the form to your webserver.
Use keyup().
function check(id)
{
document.getElementById("result").innerHTML = id;
}
<input type="text" name="test" id="test" onkeyup="check(this.value);">
Your value: <span id="result"> </span>
$(document).ready(function() {
$("#check").keyup(function(){
alert($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="check" >
For this purpose you should use .keyup function/event. Following are the snippet :
$(document).ready(function () {
$("#nama_tamu").keyup(function(){
$("#enterdata").html($("#nama_tamu").val());
$.ajax({
type: 'POST',
url: "getdata.php",
data: "nama_tamu="+$("#nama_tamu").val(),
success: function(res)
{
$("#outputdata").html(res);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<?php
session_start();
echo 'Hellow Hisoka';
?>
<form name="form" method="post">
<div class="col-sm-3">
<label class:>Nama :</label>
</div>
<div class="col-sm-9">
<input type="text" name="nama_tamu" id='nama_tamu' class="form-control" placeholder="Nama Lengkap">
<?php
$myValue = $_POST['nama_tamu'];
?>
<br> You press following character:<div id="enterdata"> </div>
</div>
<br/><br/>
<div id="outputdata"></div>
<?php
echo $myValue;
?>
</form>
Also create one file for the required output.
Now in getdata.php file
echo $nama_tamu=$_POST['nama_tamu'];

send PHP variable to javascript function via HTML

I am trying to send a PHP variable to a Javascript funtion using HTML. I dont know if it is possible or not. I am a newbie.
This is all the code in both the files, index.php and abc.php
P.S. I have changed the file name from index.html to index.php
index.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml-transitional.dtd">
<?php
require("../php/abc.php");
?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Some Title</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="file.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="here.js"></script>
</head>
<body onload="init();">
<noscript>
Your browser does not support Javascript!!
</noscript>
<table id="content">
<tr>
<td>
<div id="scroll"></div>
</td>
<td id="colorpicker" valign="top">
<img src="palette.png" id="palette" alt="Color Palette" border="1" onclick="getColor(event);" />
<br />
<input id="color" type="hidden" readonly="true" value="#000000" />
<span id="sampleText">
(text will look like this)
</span>
</td>
</tr>
</table>
<div>
<input type="text" id="userName" maxlength="50" size="10" onblur="javascript: check('<?php echo $phpVariable; ?>');" />
<input type="text" id="messageBox" maxlength="2000" size="50" onkeydown="handleKey(event);" />
<input type="button" value="Send" onclick="sendMessage();" />
<input type="button" value="Delete All" onclick="deleteMessages();" />
</div>
</body>
</html>
Javscript function
function check(param_name)
{
var oUser=document.getElementById("userName");
oUser.value = param_name;
}
abc.php
if(isset($_POST['user_name'], $_POST['action'])) {
$user_name = $_POST['user_name'];
$action = $_POST['action'];
if($action == 'joined') {
$phpVariable = user_joined($user_name);
}
function user_joined($user_name) {
$servername = "";
$username = "";
$password = "";
$dbname = "";
//Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$user_name = mysql_real_escape_string(htmlentities($user_name));
$sql = "INSERT INTO table_name (column_name) VALUES ('$user_name')";
$query = "INSERT INTO table_name2 (column_name) VALUES ('$user_name')";
$result = $conn->query($query);
if($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error in inserting: " . $sql. "<br>" . $conn->error;
}
return $user_name;
$conn->close();
}
Try something like that
HTML
<input type="text" id="nametxt" />
<button id="btn-check"></button>
Javascript
$(document).ready(function (){
$("#btn-check").click(function(){
var name = $('#nametxt').val();
var login = {
parameter: name
};
$.ajax({
type: 'POST',
url: 'file.php',
data: login,
datatype: 'json'
}).done(function(data) {
console.log(data);
});
});
});
PHP
<?php
//do some
echo information; -- this way return parameters
?>
As you have written, the way to output the value of a PHP variable to an HTML page is by doing <?php echo $phpVariable ?>. In newer versions of PHP (and in older ones where the setting was turned on), you can shorten this to <?= $phpVariable ?>.
You are getting an 'undefined variable' warning probably because the $phpVariable is not getting set. In your code, this variable is only initialized if $action == 'joined'. If you want it to have a default value, give it one first:
$phpVariable = null;
// note that three equals signs are not necessary here
// but a good habit for cases where it matters
if ($action === 'joined') { ... }
When you output the PHP variable into a JavaScript string, you should escape the output so that you don't leave your visitors vulnerable to XSS (cross-site scripting) attacks. In this case, json_encode should be sufficient. However, since your JavaScript is not within a <script> tag, but rather within an onblur attribute, you have to escape any characters which are special in HTML. Since you're using double quotes around the attribute value, htmlspecialchars is sufficient for that. So in all, you will output htmlspecialchars(json_encode($phpVariable)). The reason for all this is that you don't want to rely on your input being clean -- mistakes will be made and when they do, you don't want to let someone attack your users.
<input type="text" id="userName" maxlength="50" size="10"
onblur="javascript: check('<?= htmlspecialchars(json_encode($phpVariable)) ?>');" />
Since we've given a default value (null) for $phpVariable and we are calling the check function with it, we should add a "check" to the check function to ensure that we got a real value, like this:
// you should use camelCase or under_scores, but not both, for consistency
function check(paramName) {
// loose equals to match null or undefined
if (paramName == null) {
return;
}
var oUser = document.getElementById("userName");
oUser.value = paramName;
}
Alternatively, if you want to be really careful about your function inputs, you could verify that paramName is a string and that it has a nonzero length, but in a dynamically typed language like JavaScript, doing all these checks manually sometimes becomes a losing battle.
This is not going to work as-is because PHP is executed server-side and JavaScript is executed client-side.
In order to do this, you're going to have to make an AJAX call to a PHP file and then use JavaScript on the results.

Validating and linking to another page

I have created a login page.In whicn iam unable to link it with the next page after clicking submit button.I want to validate and redirect to the next page.ie home.php.Kindly help me find out what am i missing.
signin.php
<!DOCTYPE html>
<html>
<head>
<script>
function val()
{
var a=document.signin.user.value;
var b=document.signin.password.value;
if ( a == "admin" && b == "rec"){
alert ("Login success");
window.location = "home.php";
return false;
}
else{
alert("login failed")
}
}
</script>
<meta charset="UTF-8">
<title>LIBRARY </title>
</head>
<body>
<div class="body"></div>
<div class="grad"></div>
<div class="header">
<div>REC<span>LIBRARY</span></div>
</div>
<br>
<br>
<br>
<div class="login">
<form name="signin" method="post" onsubmit="val();">
<input type="text" placeholder="username" name="user"><br>
<input type="password" placeholder="password" name="password"><br>
<input type="submit" id="mybutton" value="login"></form>
</div>
</body>
</html>
The problem is the onsubmit event is not having false returned to it, so it posts the form normally, after your JavaScript has finished. Even in the case of successful login and the redirect is executed, the form will still submit and it will override the redirect.
Firstly, Move your return false; to the end of the function, so that it always executes.
Secondly, change your onsubmit="val();" to onsubmit="return val();". This means the onsubmit event will always be returned false and will not try to post the form.
Side note: this is by no means a secure system. Any visitor can simply observe the HTML source to find the password, or just navigate directly to home.php. For a secure system, you will need to do the authentication on the server side (in the PHP).
You could use preventDefault() Event method without using onsubmit=val() like below.
document.getElementById("signin").addEventListener("submit", function(e){
e.preventDefault()
// actual code to validate
});
or
can try some dirty work on server side directly to hide the validation part
<?php
ob_start();
session_start();
loginForm();
$userinfo = array(
'admin'=>'0b2c082c00e002a2f571cbe340644239'
);
if(isset($_POST['username'])){
if($userinfo[$_POST['username']] == md5($_POST['password'])){
$_SESSION['username'] = $_POST['username'];
header('Location: home.php');
exit();
}else{
?>
<script type="text/javascript">
alert("Oops.... User name or Pasword is worng, Please try again");
</script>
<?php
}
}
function loginForm()
{
?>
<form name="login" action="" method="post">
Username: <input type="text" name="username"> <br><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="login">
</form>
<?php
}
?>

Error: Permission denied to access property '$'

everybody.
I have the following situation:
I have:
http://example.com/ and http://example.com/new
In example.com, I have some forms that I load in example.com/new domain with fancybox iframe.
My form, basically shows some fields for the user to enter his pessoal data, like name, phone and etc... After he submit that, I show some user agreement terms that comes from database and a checkbox for the user to say that he agree with the terms.
After he check and submit, I want to alert some sucess message and the fancybox modal/iframe to close and thats it.
In the form page, i've loaded jquery, and bootstrap. So, when the user agree, I print:
<?php
echo "
<script>
alert('Some success message!');
$(document).ready(function(){
parent.$.fancybox.close();
});
</script>
";
?>
I have three forms, in one, works, in the other two, i get:
Error: Permission denied to access property '$'
The only difference between the form that works and the other two, is that in the form that works, i don't have the agreement terms coming from database, only the checkbox.
I could put my entire code here, but would be a giant question. But if you guys need, I can update.
Sorry for my english and forgive-me if I was not clear.
UPDATE:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<?php
/* Connect with DB */
require_once('require/conectar.php');
if(!empty($_POST))
foreach($_POST as $k => $v)
$$k = $v;
?>
<script type="text/javascript" src="http://example.com/new/assets/js/jquery.js"></script>
</head>
<body>
<?php if(!isset($agree) and !isset($next)): ?>
<h1>The form</h1>
<form method="post" action="">
<label>Your name:</label>
<input type="text" name="name">
<br>
<label>Your email:</label>
<input type="text" name="email">
<br>
<input type="submit" name="next">
</form>
<?php
else:
$error = (!isset($name)) ? true : false;
$error = (!isset($name)) ? true : false;
if($error)
{
echo '<script>You must fill all fields before submit.</script>';
exit;
}
$qrr = mysql_query("SELECT * FROM `terms`");
$terms = mysql_fetch_object($qrr);
?>
<h1>Terms:</h1>
<?php echo $terms->content; ?>
<form method="post" action="">
<input type="hidden" value="<?php echo $name; ?>" name="name">
<input type="hidden" value="<?php echo $email; ?>" name="email">
<input type="checkbox" value="1" name="accept"> I agree.
<input type="submit" name="agree">
</form>
<?php
endif;
if(isset($agree))
{
/*
Here i mail me the user data.
*/
echo "
<script>
alert('Soliciação Realizada com sucesso!');
$(document).ready(function(){
parent.$.fancybox.close();
});
</script>
";
}else
{
echo "<script>alert('You need to agree with the terms to proceed.');</script>";
}
?>
</body>
</html>
This is a browser security thing. While there's a few ways around it, the best one is probably to use the postMessage API.
On your example.com parent page, add some code like this:
function handleMessageFromiFrame(event) {
alert('Some success message: ' + event.data);
//$.fancybox.close();
}
window.addEventListener("message", handleMessageFromiFrame, false);
And, then on your child example.com/new iframe, add code like this:
var parentOrigin = "*"; // set to http://example.com/ or whatever for added security.
function sendMessageToParent(){
parent.postMessage("button clicked", parentOrigin);
}
$('#submit-btn').click(sendMessageToParent);
Here's an example of it in action:
Parent example.com page: http://jsbin.com/hiqoyevici/1/edit?html,js,output
Child example.com/new iframe: http://jsbin.com/goferunudo/1/edit?html,js,output
When you click the button in the child page, it uses postMessage to notify the parent. Then the parent listens for the message and does whatever action you want.

Categories

Resources