Question as stated above. I am using older browsers (IE8 and FF8) due to corporate policy. I can't fix this but my research says this isn't the issue...(yeah right;)
I'm using PHP 5.5.12 on Apache 2.4.9 with a MySQL (5.6.17) back end. The site is a CMS that has grown organically over several years.
I have a user admin page that adds, updates, and deletes accounts. However, no matter what I have done the form submits. The worst example is if the admin chooses to delete an account and when asked 'Do you really wish to DELETE...?' and cancels, it is still deleted! I've copied my JavaScript and an excerpt from the PHP/HTML below.
I have tried a few changes to my JavaScript like returning after setting the window.event.returnValue but I've always gotten the same results. I've been reading for several days now and keep coming up blank! I've tried onSubmit instead of onClick but it really doesn't suit the site, besides it didn't work either.
I'm beginning to think the age of the browsers is the issue. I run this with Safari on my home development box fine. Any help would be appreciated.
JavaScript
<script language="JavaScript">
function frmVerify(check, loginid, login) {
if (check == 'add') {
Uname=add_user.login_name.value;
Pass1=add_user.password.value;
Pass2=add_user.password2.value;
if(Uname=='') {
alert('A user name must be assigned to an account.');
window.event.returnValue=false;
}
if(Uname == login) {
alert('You cannot create an account with your own username (' + login + ')');
window.event.returnValue=false;
}
if(Pass1 != Pass2) {
alert('Entered passwords are not the same! Make sure the password and verification fields match.');
window.event.returnValue=false;
}
if(Pass == '') {
alert('Assigning a password is required when creating an account!');
window.even.returnValue=false;
}
} else if(check == 'update') {
Uname=eval('edU_'+loginid+'.login_name.value');
Pass1=eval('edU_'+loginid+'.password.value');
Pass2=eval('edU_'+loginid+'.password2.value');
if(Uname == '') {
alert('A user name must be assigned to an account.');
window.event.returnValue=false;
}
if(Pass1 != Pass2) {
alert('Entered passwords do not match! Make sure the passowrd and verification fields match.');
window.event.returnValue=false;
}
} else if(check == 'del') {
Uname=eval('edU_'+loginid+'.login_name.value');
if(Uname == '') {
request = 'Do you really wish to DELETE this user account?';
} else {
request = 'Do you really wish to DELETE user: ' + Uname + '?';
}
var answer = confirm(request);
if(answer) {
window.event.returnValue=true;
} else {
window.event.returnValu=false;
}
}
}
</script>
In the PHP/HTML I have
echo "<form name=\"delU_$login_id\" id=\"delU_$login_id\" mehtod=\"POST\">";
echo "<input type=\"image\" src=\"./images/delete.png\" value=\"Delete\" onClick=\"return frmVerify('del', '$login_id', '$username');\">";
echo "</form>";
window.event.returnValue (which you don't always spell correctly anyway) is non-standard and shouldn't be used.
You're using 1990s style intrinsic event attributes instead of addEventListener, so just:
return false;
If you were using addEventListener then you would:
event_object.preventDefault();
where event_object is the first argument to your event handler function.
Related
Something's not working this morning and I'm pretty sure it's my brain. I've got a form that tracks changes to a field under certain conditions:
-If the status = Draft, do nothing.
-If the status = Approved, prompt user to ask if they are sure they want to make the change.
-If they click 'OK', it should call the process that records the change.
-If they click 'Cancel' it should do nothing.
-If the status is anything other than draft or Approved, don't prompt but call the process that records the change.
I had the code recording changes in non-draft status, but after I added the ==true to the end of the confirm statement, everything stopped working.
var stat = $('#status').text();
var parms = just a bunch of parameters i'm passing to the url below;
if (stat=='(Draft)'){
//do nothing
}
else if (stat !== 'Approved' && stat!== '(Draft)'){
var url = webDbName + '/(CreateOTChangeRecordOnChange)?OpenAgent' + parms;
$.get(url, function(data) {
$('#tableBodyChanges').html(data);
});
}
}
else if (stat == 'Approved' && confirm('You are changing the hours on a request that has already been approved. This will send a notification to the department director. Proceed?')==true) {
var url = webDbName + '/(CreateOTChangeRecordOnChange)?OpenAgent' + parms;
$.get(url, function(data) {
$('#tableBodyChanges').html(data);
});
} else {
//do nothing });
}
It is working, but you could just ommit the == true because it already is a "if-able boolean"
if(confirm("test?")){
console.log("confirmed1");
}else {
console.log("notconfirmed1");
}
<!-- or the other way arround -->
if(!confirm("test?")){
console.log("notconfirmed2");
}else {
console.log("confirmed2");
}
<!-- it should also work the way you posted as well -->
if("foo" == "foo" && confirm("test?") == true){
console.log("confirmed3");
}else {
console.log("notconfirmed3");
}
I'm currently configuring my "User Registration" form in PHP.
Trying to create a simple function to check if the username already exists in the database
After doing my research, I have found that there are several ways this can be done.
(a) the best way is probably to use a PHP/AJAX combination, to check right away if the username already exists (in other words, the check is done BEFORE the user clicks the "Submit" button;
(b) the other way is to do a simple SQL-query, which will return an error message, if that particular username already exists in the database. (The only drawback with this method is that : the check is done only AFTER the user clicks the "Submit" button.
I would have preferred Option A, of course. But, I was unsuccessful in my attempts to create a working AJAX/jQuery script.
So, I went with Option B instead.
And, I got it working.
Here is the simply query I used :
if(isset($_POST['submit1'])||isset($_POST['submit1'])) {
$login = $_POST['login'];
$query_login = "SELECT login FROM registration WHERE login='$login';";
$result_login = mysqli_query($conn,$query_login);
$anything_found = mysqli_num_rows($result_login);
//check if the username already exists
if($anything_found>0)
{
echo "Sorry, that Username is already taken. Please choose another.";
return false; }
else { //proceed with registration
It worked fine. The error was displayed.
The only problem is : the registration form itself disappeared.
I would have liked to display the error on the same page as the registration form, without having to RESET or somehow GO BACK.
I know that the reason for this is something very minor (and kinda stupid on my part :D :D)
Probably something to do with that "return false" thingy at the end of the query.
But, I am not sure.
(a) How can I get the error message displayed on the form-page itself?
(b) Or, better yet, is there a JavaScript Function I can use for this, so that I can simply call the function in the "Submit" button................like so : onSubmit = return function() ??
Thanks
UPDATE: Here is my form code.
form action="myform.php" method="post">
<br>
Choose a username : <input type="text" name="login" value="<?=$login?>"
required>
UPDATE
I was able to find the following jQuery code :
$(document).ready(function() {
//the min chars for username
var min_chars = 3;
//result texts
var characters_error = 'Minimum amount of chars is 3';
var checking_html = 'Checking...';
//when button is clicked
$('#check_username_availability').click(function(){
//run the character number check
if($('#username').val().length < min_chars){
//if it's bellow the minimum show characters_error text '
$('#username_availability_result').html(characters_error);
}else{
//else show the cheking_text and run the function to check
$('#username_availability_result').html(checking_html);
check_availability();
}
});
});
//function to check username availability
function check_availability(){
//get the username
var username = $('#username').val();
//use ajax to run the check
$.post("check_username.php", { username: username },
function(result){
//if the result is 1
if(result == 1){
//show that the username is available
$('#username_availability_result').html(username + ' is
Available');
}else{
//show that the username is NOT available
$('#username_availability_result').html(username + ' is not
Available');
}
});
}
I assume that, for my particular example :
(a) the jQuery file cannot be inserted into the actual PHP file (my php file is named : registration.php, which includes both the html and php);
(b) this particular jQuery file includes a "button", which needs to be clicked to check if the username already exists. This is not a bad idea; but, I would rather that this was done automatically, without the need to click on a button (let's face it : there are some users out there who are indeed too clueless to perform this simple check manually). My aim is free the user as much as possible from the need to do such trivial tasks :D
Anyway, my point is : so as to eliminate the need for a button, I would like to include an auto-function which checks once the user types in the username.
According to Google, the following function is what I need :
Replace $(‘#check_username_availability’).click(function(){ … with $(‘#username’).keyup(function(){ …
(c) Isn't there any way to actually insert that JQUERY into "registration.php" ?? Or, should it be a separate file entirely?
The better way would be you bind the ".blur" event on which you may check if the username is valid via ajax. Don't forget to check the username after form submission at before form submission.
Below your input box create a
<span class= "error">Username is already present. </span>
<span class= "success">Username can be assigned. </span>
and just display the message accordingly.
You may use the script as
$.ajax({
url : "check_username.php",// your username checker url
type : "POST",
data : {"username",$("input.username").val()},
success : function (data)
{
if(data == "success")
{$(".success").show();$(".error").hide();}
else
{$(".error").show();$(".success").hide();}
},
});
You php code would be something like this :
$query = "SELECT username FROM tab_users WHERE username = '".$_POST['username']."'";
$result_login = mysqli_query($conn,$query_login);
$anything_found = mysqli_num_rows($result_login);
//check if the username already exists
if($anything_found>0)
{
echo "fail";
return false;
}
else
{
echo "success";
return false;
}
You can disable the submit button and add a span message near the input field.
Check this code:
function checkUsername()
{
var username = document.getElementById('username');
var message = document.getElementById('confirmUsername');
/*This is just to see how it works, remove this lines*/
message.innerHTML = username.value;
document.getElementById("send").disabled = true;
/*********************************************/
$.ajax({
url : "check_username.php",// your username checker url
type : "POST",
data : {username: username},
success: function (response) {
if (response==0)
{
message.innerHTML = "Valid Username";
document.getElementById("send").disabled = false;
}
if (response==1)
{
message.innerHTML = "Already Used";
document.getElementById("send").disabled = true;
}
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<label for="uername">Username:</label>
<input type="text" class="form-control" name="username" id="username" onkeyup="checkUsername(); return false;" required/>
<span id="confirmUsername" class="confirmUsername"></span>
<button type="submit" id="send" name="action" value="Send">Send</button>
put this
include([your validating php file]);
and in your form action link to your login form file.
note : your login file have to be php file.
I've looked around different questions relating this topic, but none have what I need. I seems simple, but it's still not working. Logically I thought it would work. I have a login form, where I query a select for the user and the password, after that I check if the user and the pw are empty, if not I check if it's in the data base. If it's in the data base redirect somewhere else. Here's the thing, when I load the page, I don't see the txtBox or anything. If I delete the php chunk, everything works fine. Any advice or help would be appreciated.
What I wrote:
<html>
<head>
<link rel = "stylesheet" href = "longInStyle.css">
<script>
function fieldValidation()
{
if( document.getElementById("username").value == "" || document.getElementById("username").value == " " )
{
alert("The username field is empty. Please, enter a username");
document.getElementById('username').focus();
return false;
}
else if(document.getElementById("password").value == "" || document.getElementById("password").value == " " )
{
alert("The password field is empty. Please, enter a password");
document.getElementById('password').focus();
return false;
}
else
{
<?php
include 'config.php';
$usr = $_POST["username"];
$pass = $_POST["password"];
$usrCount = 0;
$passCount = 0;
$SQLUsr = " SELECT USERNAME FROM Users WHERE USERNAME = '$usr' ";
$result = mysql_query($SQLUsr);
$SQLPass = " SELECT PASSWORD FROM Users WHERE PASSWORD = '$pass' ";
$result2 = mysql_query($SQLPass);
$usrCount = mysql_num_rows($result);
$passCount = mysql_num_rows($result2);
if($result == 1)
{
$SQLLvl = " SELECT USERLEVEL FROM Users WHERE USERNAME = '$usr' ";
$result3 = mysql_query($SQLLvl);
if($result2 == 1)
{
if($result3 == "Super")
{
header("location:superUserMain.html");
}
else
{
header("location:editMain.html");
}
mysql_close($db_handle);
}
else
{
<script>
alert("The wrong password.");
document.getElementById('password').focus();
</script>
}
}
else
{
<script>
alert("The wrong username.");
document.getElementById('username').focus();
</script>
}
?>
return true;
}
}
</script>
</head>
<body>
<form method = "post" onsubmit = " return fieldValidation()">
<div>
<div>
Username
</div>
<input type = "text" name = "username" id = "username">
</div>
<div>
<div>
Password
</div>
<input type = "password" name = "password" id = "password">
</div>
<div>
<input type="submit" id = "logIngBtn" name = "logInBtn" value = "Login">
</div>
</form>
</body>
</html>
I saved it as a php file.
config.php has the data base credentials. Username, password and everything else to access it.
To expand on John Condes comment:
You're using JavaScript to control whether PHP code will be executed. This isn't possible (at least not in the way you're trying to do it). PHP code runs on the server, before anything is sent to the client (the users browser). JavaScript (in your context, at least) only runs in the client (the users browser). By the time your JS decides whether the PHP should run, it's too late. The browser has no understanding of the PHP code you're giving it.
I'd suggest starting with a good tutorial on how to build an AJAX login form with PHP and MySQL.
Ignore the haters man...
To help you out though it might be a idea to do what John Conde and mchandleraz said. But to be fair if you are new to this then I think you are doing really well... I still use procedural code as I'm still learning and none of my code is live.
Jay Blanchard is right though mysql_ functions and procedural code is being deprecated and can pose a massive security risk on a live site as someone could potentailly hack your database and steal or your customers information for example. BTW don't take comments on here to heart, programmers tend to be straight talking people by nature.. so don't be surprised if you do something wrong to get slammed for it!
In regards to your question though there are a ton of youtube videos that you can follow on this kind of stuff... failing that buy a book.
Hope you resolve your issue.
Happy coding! :)
I took the following code from another webpage "http://www.javascriptkit.com/script/cut10.shtml".
<SCRIPT>
function passWord() {
var testV = 1;
var pass1 = prompt('Please Enter Your Password',' ');
while (testV < 3) {
if (!pass1) history.go(-1);
if (pass1.toLowerCase() == "letmein") {
alert('You Got it Right!');
window.open('protectpage.html');
break;
}
testV+=1;
var pass1 = prompt('Access Denied - Password Incorrect, Please Try Again.','Password');
}
if (pass1.toLowerCase()!="password" & testV ==3) history.go(-1);
return " ";
}
</SCRIPT>
<CENTER>
<FORM>
<input type="button" value="Enter Protected Area" onClick="passWord()">
</FORM>
</CENTER>
It works only in case the password is entered second time, but not when it is entered first time. When you enter password it says wrong password prompting you to enter the password again and then it goes through.I need a script that shall prompt me of the correct password, in case I enter the wrong password. Can any one help me with the code as i am a beginner in JavaScript.
Your code appears to work when visiting the link.
I know you're learning. Still, you shouldn't be doing authentication like this though as you're not really protecting anything. Anyone can read the source code by using the "View Page Code" option in any browser (typically right click on the page). This means anyone can easily get your password.
For true authentication you should be using either a server side language (like PHP), or HTTP Digest authentication configured by your web server. Digest is a bit out of date as it uses MD5, but it's a million times better than what you're doing.
For more information about setting up HTTP Digest with Apache web server see:
http://httpd.apache.org/docs/2.2/mod/mod_auth_digest.html
For doing the same with Nginx:
http://wiki.nginx.org/HttpAuthDigestModule
The HTTP Basic authentication works too, but it transmits the password from the user's browser in plain text. With HTTP digest the password is hashed.
Knowing that you're learning JavaScript, your best bet is to configure the web server you're using. Since most web hosting services use Apache, you can most likely use an .htaccess file. You can search ".htaccess http digest" for tutorials on how to set this up.
Some web hosting services have control panels that have a feature to protect directories using Digest/Basic auth. In cPanel, which is quite common, it's called "Password Protect Directories".
If you were more advanced I would suggest doing it in PHP, but thats a rather complicated subject.
//Add this to you script
function run(){
var password = prompt("Password Please");
//Change to your own Password
if(password != 'Sameer'){
document.body.innerHTML = '';
document.body.innerHTML = 'Password Failed! Reload to Renter Password';
}else{
alert('Success');
}
}
run();
Try this.. Just add access denied prompt inside the false case...
function passWord()
{
var testV = 1;
var pass1 = prompt('Please Enter Your Password',' ');
while (testV < 3)
{
if (!pass1)
{
history.go(-1);
var pass1 = prompt('Access Denied - Password Incorrect, Please Try
Again.','Password');
}
else if (pass1.toLowerCase() == "letmein")
{
alert('You Got it Right!');
window.open('protectpage.html');
break;
}
testV+=1;
}
if (pass1.toLowerCase()!="password" & testV ==3)
history.go(-1);
return " ";
}
I used the same exact code that you have and the problem is the the first time for don't know what reason it added one space in front of the input. Just make sure that you don't have that and it will be fine.
If you use a library to render the UI, you can use this function:
export function setPasswordToEnter({
password,
localStorageKey,
errorMessage,
}) {
if (
!password ||
(localStorageKey && localStorage.getItem(localStorageKey) === password)
) {
return;
}
const input = prompt('Enter the password to continue:');
if (input !== password) {
alert(errorMessage || 'Incorrect password');
throw new Error(errorMessage || 'Incorrect password');
}
if (localStorageKey) {
localStorage.setItem(localStorageKey, input);
}
}
Run before the render function:
setPasswordToEnter({
password: 'password',
localStorageKey: '[myapp] password to enter'
});
React Example: https://stackblitz.com/edit/password-to-enter-react?file=src/index.js
P.S. You should definitely get your password from env variable if possible.
I need to tack some simple password protection onto arbitrary html files. It does need need to be secure, but just keep out the random roff-raff. I tried using the below JS:
var password;
var thePassword="secretpassword";
password=prompt('Enter Password',' ');
if (password==thePassword) { alert('Correct Password! Click OK to Enter!'); }
else { window.location="http://www.google.com/"; }
This works fine in Firefox, but seems that the prompt function fails in IE and so we always redirect to google...
Any suggestions on how to do a simple password protection using straight HTML pages?
EDIT: to be clear, it works fine in Firefox, and in IE does not even prompt with a popup asking to "Enter Password"
Works fine for me in IE. Demo: http://jsfiddle.net/U2n3P/
One possible reason it may not be working is that you're populating the prompt with an empty space, by using ' ', so when you start typing there may be a space at the end. Change the prompt to:
password=prompt('Enter Password', '');
FYI, I know you said you didn't need this to be super secure, but you might as well add some security. Get an MD5 library and do, instead:
var thePassword = "md5encodedpassword";
password=prompt('Enter Password',' ');
if(md5(password) != thePassword){
Name the secure page or directory the md5 hashed password.
function isThere(url) {
var req= new AJ(); // XMLHttpRequest object
try {
req.open("HEAD", url, false);
req.send(null);
return req.status== 200 ? true : false;
}
catch (er) {
return false;
}
}
password=prompt('Enter Password',' ');
password=md5(password);
if (isThere(md5 + "/") { window.location = password + "/"; }
else { alert("incorrect"); }