How to check if USERNAME already exists in PHP/MYSQL? - javascript

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.

Related

I am Having Problems Updating My MySQL table value From my Modal form Sing PHP

I created a modal form (that pops up upon a link click, i.e trigger()). This is the HTML code:
<div class="modalbg">
<div class="modalPopup">
<form action="samepage.php" class="formContainer" method="post">
<h2>Change Desk Number</h2>
<label for="studentid">
<strong></strong>
</label>
<input type="password" placeholder="Your KEY" name="studentid" required/>
<label id="status" style="color:red;"></label>
<button type="submit" class="btn" onclick="return verify()">Upgrade</button>
<button type="button" class="btn cancel" onclick="closeForm()">Close</button>
</form>
</div>
</div>
The JavaScript that controls this modal is:
function trigger(){
document.getElementById("modalPopup").style.display = "block";
}
function closeForm() {
document.getElementById("modalPopup").style.display = "none";
}
function verify() {
var studentid = document.getElementById("studentid").value;
if (studentid != dbstudentid || !studentid){
document.getElementById("status").innerHTML="Invalid Student ID!";
function trigger(event) { event.preventDefault(); }
return false;
}
else{
document.getElementById("modalPopup").submit();
}
}
Everything works at this point (i.e it pops up whenever I click the link and whenever I knowingly try to enter a wrong studentid, it returns the "Invalid student ID" on the "status" label. (Note: I had already saved the session's student ID in the variable dbstudentid using:
var dbstudentid = <?php echo json_encode($dbstudenid);?>;
My problem however comes from when I try to execute the PHP on the same page.
Whenever I insert the PHP code into the modalbg div or modalPopup div inside it, the entire modal refuses to pop, let alone submit.
This is the PHP code I used (it should be noted that at the beginning of the page, I had already used include(configure-db.php) and session_start() ) :
<?php
if(isset($_POST['studentid'])){
$studentid = $_POST['studentid'];
$desk = 1;
$deskstatus ="";
$select = "UPDATE users SET deskNo = '$desk' WHERE name='$SESSION';
}
if (mysqli_query($MyConn, $select)) {
$deskstatus = "Desk changed successfully!";
} else {
$deskstatus = "Error";
} return $deskstatus;
?>
I have tried everything, the modal just refuses to come every time, let alone successfully make the Desk Update on my Database. to make things worse, whenever I refresh the page, the modal which I set to display:none; by default on CSS suddenly starts showing. But whenever I remove the PHP code, it returns to normal.
Do I need to make the action execute in a separate page? If yes, please how?
Else, how please?
I world highly suggest you think about using AJAX to handle this probolem.
let's clear up things.
you can write var dbstudentid = '<?= $dbstudenid ?>'; instead of var dbstudentid = <?php echo json_encode($dbstudenid);?>; this will give you freedom of JS native datatype.
you need to send this form request through ajax and recive output there.
Change the php code else part to like this
else { $deskstatus = "Error: " . mysqli_error($MyConn); }
Now when there is a actual problem on code you will know what was the problem. and it will not break you interface.
4. Create seperate file that handle this form request.
5. Here is code snippet of plaing JS AJAX implementation
let post = JSON.stringify(postObj)
const url = "https://jsonplaceholder.typicode.com/posts"
let xhr = new XMLHttpRequest()
xhr.open('POST', url, true)
xhr.setRequestHeader('Content-type', 'application/json; charset=UTF-8')
xhr.send(post);
xhr.onload = function () {
if(xhr.status === 201) {
console.log("Post successfully created!");
let AlertDiv = document.querySelector('#alert');
AlertDiv.innerHTML = xhr.response;
}
}

PHP with javascript

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! :)

Password Protect Page

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.

Display a 'Page Loading' message between pages

I have a form on my site that when submitted takes the user from Page1.html to Page2.html.
I would like to display a message between the form being submitted and "Page2 loading".
Can someone provide me with an example of this?
If your form submit data via ajax then you could try something this:
$('form#myform').submit(function(e) {
e.preventDefault();
$('#message').html('Sending....'); // #message may be a div that contains msg
$ajax({
url: 'url_to_script',
data: 'your_data',
success: function(res) {
// when submit data successfully then page reload
window.location = 'page2.html'
}
});
});
What you're looking to do can't be done by standard form submission.
You'll want to submit the form using ajax, and display a "Please wait" message while you are waiting for a response. Once the response is received and validated to be OK, you can then redirect the user to the page you now call page2.
The easiest way to submit a form via ajax is to serialize it to a string and pass it along. Then, you'll need a page to process the received data, and return an OK or and ERR.
The JS will then need to decipher next action.
This is not tested, but copied and pasted from various working projects.
You'll need to download and include the json2.js project.
page1
<div id='pleaseWait'>Please Wait...</div>
<form id="theForm" onsubmit="doAjaxSubmit();">
<input type='text' name='age' id='age' />
<input type='submit' value='submit'>
</form>
<script type="text/javascript">
function doAjaxSubmit(){
var j = JSON.stringify($('#theForm').serializeObject());
$('#pleaseWait').slideDown('fast');
$.post('processor.php?j=' + encodeURIComponent(j), function(obj){
if(obj.status=='OK'){
window.location='page2.php';
}else{
$('#pleaseWait').slideUp('fast');
alert('Error: ' + obj.msg);
}
}, 'json');
return(false);
}
$.fn.serializeObject = function(){
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
</script>
processor.php
<?php
$j=json_decode($_POST['j'], true);
if ((int)$j['age']<=0 || (int)$j['age']>120){
$result = array('status'=>'ERR', 'msg'=>'Please Enter Age');
}else{
//Do stuff with the data. Calculate, write to database, etc.
$result = array('status'=>'OK');
}
die(json_encode($result));
?>
This is essentially very similar to the answer below (by #thecodeparadox), but my example shows how to pass the entire for without having to manually construct your data object, shows how to validate on the PHP side as well as return the appropriate JSON data to either redirect the user, or to display an error, and uses animations to display the message.

Form submit add domain to username field if missing

I have a login form that includes a username and password field.
Users will be able to login using:
Domain\username
And
Username#domain.org.uk
However many users attempt to login using just 'username'
I want to help users by adding domain\ or #domain.org.uk to there username when they enter just 'username', when they click the login button I want to add the domain part of the username.
How can I do this in pure JavaScript?
function insertDomain (){
var txtBox = document.getElementById('Your_Textbox');
if(txtBox.value.indexOf("#") == -1)
{
txtBox.value += "#domain.org.uk";
}
}
On Submit: http://alexking.org/blog/2003/10/01/javascript-onsubmit-handler
Something along the lines of
var username = document.getElementById('username')
if(username.indexOf('#') < 0){
username = usename + '#domain.org.uk';
}

Categories