Login without clicking submit - javascript

so I'm working on this project in which I made an admin area.
While I was working on the login functionality, I wanted a feature like this :-
As soon as the user fills all the entries (Username and Password), the system automatically logs him in.
He doesn't need to hit the submit button.
Similarly, he should be given an error message if the password was incorrect.
How can I achieve this functionality ?
I guess it could be done via jQuery and Ajax, and I have nil knowledge in both of them.
If anybody could guide me in the correct direction, it would be great.
Admin_login.php
<form class="form-horizontal" action="****" method="post" id="login">
<fieldset>
<div class="input-prepend" title="Username" data-rel="tooltip">
<span class="add-on"><i class="icon-user"></i></span><input autofocus class="validate[required] text-input, input-large span10" name="username" id="username" type="text" placeholder="Username"/>
</div>
<div class="clearfix"></div>
<div class="input-prepend" title="Password" data-rel="tooltip">
<span class="add-on"><i class="icon-lock"></i></span><input class="validate[required] text-input, input-large span10" name="password" id="password" type="password" placeholder="password"/>
</div>
<div class="clearfix"></div>
<div class="clearfix"></div>
<p class="center span5">
<button type="submit" class="btn btn-primary">Login</button>
</p>
</fieldset>
</form>
Database Table
Column Name Type
Username VARCHAR
Password VARCHAR

I wrote a git.
This is the link:
https://github.com/FabioSorre/HTML-PHP-AJAX-JQUERY-JS
The steps are these:
Html: No form action (action="") and specify method (Client-side)
Javascript/Jquery: onSubmit function call (Client-side)
Setup JSON callback (Client-side)
Php file (set json_encode, the operations and response(s)) (Server-side)
Show the results (Client-side)

Try using setInterval() that executes a function that checks if both fields are filled every 100MS. Please not this is a dirty hack. I would suggest using better validation methods. Google can help u with that
<script>
function checkCompleteness(){
if($('#username').val()!=='' || $('#password').val()!==''){
//POST DATA HERE MAYBE WITH AJAX OR TRIGER SUBMIT(GOOGLE HOW)
$.post(
'my/endpoint',
{
username:$('#username').val(),
password: $('#password').val()
}, function(response){
// ACT ON RESPONSE STATUS
});
}
//CHECK BOTH FIELDS EVERY 100 MS
setInterval(checkCompleteness(), 100);
</script>

Ok so I'm thinking a little out loud but I hope this guides you to the right direction.
Let's assume that when you are logging in you type a character at maybe 1 sec delay. Let's assume that when the user finishes typing the Password, 2 or 3 seconds will pass. You can make a listener that waits for 2 seconds to pass after the password is typed and then trigger the submit file. Of course you should check that the username is also typed (min characters and not empty exception).
You can make the 2 second listener like this:
Javascript code:
// Trigger a callback function after a given time
var wait = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
// Trigger the submit via AJAX
wait(function(){
// form validation
$.ajax({
url: '/Admin_login.php',
type: 'POST',
dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',
data: {
username: $('#username').val(),
password: $('#password').val()
},
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
}, 2000); // It submits the form via AJAX after 2 seconds have passed since
// the user typed something in the password field
Admin_login.php
The PHP part is more of a sketch but I hope you understand the idea behind it
<?php
$username = $_POST['username'];
$password = $_PSOT['password'];
//some more forom validation
$loggedin = login($username, $password);
if ($loggedin) {
// Loggedin
}
else {
// renegerate form
}
?>
P.S. Don't forget to avoid SQL injection and escape any special characters, some more information about this topic here: How can I prevent SQL injection in PHP?
Keep me posted and good luck! :)

Related

Javascript XMLHttpRequest and Jquery $.ajax both are returning the current page HTML code

The problem
Hello i want to start off hoping all of y'all are having a fantastic day! I'm having a really weird problem that i have never came across before. I have a bootstrap navigation form with two fields, an input for a email and a field for the password.
When the user submits the form it calls to an AddEventListener which is waiting for a click of the login button. and after that is called it validates(Server Side Validation) the form of the entered data. After both the email_validated and password_validated is both equal to true it calls to a function called checkLogin(email, password){email = entered email in field, password = entered password in field}. In the checkLogin function it called to a JQuery $.ajax({}) call which sends the email and password field to a php document located in /scripts/checkLogin.php. However instead of it returning "Hello"(For testing purposes) is returns the entire HTML code for the current page(As shown above)
JQuery $.ajax({}) code
Here i have the code for the $.ajax({}) call.
Console
I'm not getting any errors in the console except for the XHR finished loading: POST
Other Pictures
Here are some other pictures that i am including to hopefully give yall a better idea of the structure.
Note
I just want to add that i have checked Stackoverflow for similar problems and other people have had this problem but they solutions did not work on my code. I have also tried just using a regular XMLHttpRequest and the same problem occurred, i'm honestly not sure what is wrong with the code for i have never had this problem before. Thank you for taking the time to read this i appreciate any help that i can get with solving this. I'm not the best with $.ajax({}) or XMLHttpRequest and im willing to make any changed to the code to try to get this to work. Below is my code for the entire javascript validation(server side).
Code
<form class="form-inline my-2 my-lg-0" method="POST">
<input class="form-control mr-sm-2 nav-login" type="text" autocomplete="off" placeholder="Email" name="email" value="trest#gmail.com" id="email">
<input type="password" name="password" autocomplete="off" class="form-control nav-login mr-sm-2" placeholder="Password" value="password" name="password" id="password">
<button class="btn btn-success my-2 my-sm-0 nr" type="button" name="login_button" id="login_button">Login <i class="fas fa-sign-in-alt"></i></button>
</form>
<script>
document.getElementById('login_button').addEventListener('click', (e) => {
e.preventDefault();
// const email_regex = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
let email_validated = true;
let password_validated = true;
let email = document.getElementById('email');
let password = document.getElementById('password');
// let email_length = email.value.length;
// let password_length = password.value.length;
//
//
// if(!email_length){
// email.classList.add('is-invalid');
// }else{
// if(!email_regex.test(email.value)){
// email.classList.add('is-invalid');
// }else{
// email.classList.remove('is-invalid');
// email.classList.add('is-valid');
// email_validated = true;
//
// }
// }
// if(!password_length){
// password.classList.add('is-invalid');
// }else{
// password.classList.remove('is-invalid');
// password.classList.add('is-valid');
// password_validated = true;
// }
if(email_validated === true && password_validated === true){
checkLogin(email.value, password.value);
}
});
function checkLogin(email, password){
$.ajax({
type: "POST",
url: '/scripts/checkLogin.php',
data: {
'email': email,
'password': password
},
contentType: "application/json; charset=utf-8",
success: (result) => {
alert(result);
}
});
}
</script>
Links to the other StackOverFlow question
ajax returns the html code of current page instead of json
I was the way my server was configured with xammp as t.niese said.

Why won't this script load?

I have a contact us form:
<form id="contactus" name="contactus" action="html_form_send1.php" method="post">
<label for="name">Name:</label><br />
<input type="text" id="name" name="name" maxlength="50" size="59" autofocus required/><br /><br />
<label for="email">E-Mail Address:</label><br />
<input type="email" id="email" name="email" maxlength="50" size="59" required/><br /><br />
<label for="question">Question:</label><br />
<textarea id="question" name="question" maxlength="1000" cols="50" rows="6" required></textarea><br /><br />
<input class="c1_scButton" type="submit" id="submit" name="submit" value="Send" />
</form>
I want it to call my mail PHP script using this AJAX code:
var msg = "";
name = $("#name").val();
email = $("#email").val();
question = $("#question").val();
//validation phase
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([az]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
function validate(e) {
if (name == "") {
msg = " valid name";
}
if (!isValidEmailAddress(email)) {
msg = msg + " valid email address";
}
if (question == "") {
msg = msg + " valid question or comment";
}
}
// on submit, Validate then post to PHP mailer script
$(function() {
$("#contactus").on('submit', function(e) {
e.preventDefault();
validate(e);
if msg != "" {
e.preventDefault();
$("#alert").html "Please enter a" + msg;
} else {
$.post('/html_form_send1.php', $(this).serialize(), function(data) {
$('#alert').css(color: "black")
$('#alert').html("<h2>Thank you for contacting us!</h2>")
.append("<p>We will be in touch soon.</p>");
}).error(function() {
$('#alert').css(color: "red")
$('#alert').html("<h2>Something went wrong. Your Question was not submitted. /n</h2>").append("<p>Please try again later or email us at <a href=href="
mailto: support# allegroaffiliates.com ? Subject = Contact Us Form " target="
_top ">support#allegroaffiliates.com.</a> </p>");
});
};
});
});
The script is called at the bottom of the HTML page after another script, but it isn't loading. I suspect that it is due to a code error but I can't find the error. Can anybody give me an idea why it wont load?
Side note: I do know that HTML5 will validate the script, but I have the validation in place for when HTML5 is not available.
Thank you for your help.
A few troubleshooting suggestions:
(1) When specifying the ajax processor file, either this $.post('html_form_send1.php' or this $.post('./html_form_send1.php' but not this $.post('/html_form_send1.php'
(2) Instead of using the shortcut code $.post(), use the full form of the method until you are pretty good at it:
var varvalue = $('#first_name').val();
var nutherval = $('#last_name').val();
$.ajax({
type: 'post',
url: 'your_secondary_file.php',
data: 'varname=' +varvalue+ '&lname=' +nutherval,
success: function(d){
if (d.length) alert(d);
}
});
(3) Disable validation routine until the rest is working, then work on that when you know everything else is working correctly
(4) Change your ajax processor file html_form_send1.php to just echo back a response to make sure you've got the AJAX working. Then, once you get the response, change it to echo back the variable you are sending. Then build it into the final desired product. But initially, something dead simple, like this:
your_secondary_file.php:
<?php
$first_name = $_POST['varname'];
$last_name = $_POST['lname'];
echo 'Received: ' .$first_name .' '. $last_name;
die();
(5) Instead of using .serialize(), initially just grab one or two field values manually and get that working first. Note that .serialize() produces JSON data, while the simpler method is straight posted values, as in sample code in this answer. Get it working first, then optimize.
(6) Note that the dataType: parameter in the AJAX code block is for code coming back from the PHP side, not for code going to the PHP side. Also note that the default value is html, so if you aren't sending back a JSON object then just leave that param out.
(7) In my AJAX and PHP code samples above, note the correlation between the javascript variable name, how it is referenced in the AJAX code block, and how it is received on the PHP side. I was very deliberate in the names I chose to allow you to follow the var name => var value pairing all the way through.
For example, the input field with ID first_name is stored in a variable called varvalue (dumb name but intentional). That data is transmitted in the AJAX code block as a variable named varname, and received on the PHP side as $_POST['varname'], and finally stored in PHP as $first_name
Review some simple AJAX examples - copy them to your system and play with them a bit.

Form validation not working with progressButton js

I've been working on this website with an animated submit button with a 3d built-in proggress bar:
http://add.digital/contato.php
For the submit button, I used this plugin:
http://tympanus.net/codrops/2013/12/12/progress-button-styles/
Everything works beautifully, the loading bar runs smoothly and there are no problems with the form submission. The problem is the validation, which doesn't seem to work. The submit button ("Enviar") is a button tag. When I change it for an input tag, validation works, but the proggress bar doesnt, and vice-versa. I've tried reproducing the effect with an input tag, but it didn't work. So I tried to work on the form validation, which seemed more approachable. I've run quite a few solutions I found here on SO and on other websites regarding form validation with button tags, but I got pretty much the same result from all of them: when hitting the submit button, the error messages for empty fields are shown, but noe of them stops the progress bar animation and the form submission. I've also searched for queries related to Ladda.js, which is a similar plugin, but I can't find a way to validate the form and stop the animation and submission when necessary. I've checked the entire code (as a newbie), and tried many different solutions, but wasn't able to sort this matter, which is quite annoying. Any help or guidance on how to gou about with this would be much appreciated.
Below is the form:
<form action="envia_mail_a2.php" method="POST">
<div class="input-group">
<label for="nome" class="hidden"></label>
<input class="input-custom" type="text" placeholder="Nome" name="edtNome" id="edtNome" required>
</div>
<div class="input-group">
<label for="email" class="hidden"></label>
<input class="input-custom" type="text" placeholder="E-mail" id="edtEmail" name="edtEmail" required>
</div>
<div class="input-group">
<label for="telefone" class="hidden"></label><input class="input- custom" type="text" placeholder="Fone" id="edtTelefone" name="edtTelefone" required>
</div>
<div class="input-group">
<label for="mensagem" class="hidden"></label>
<textarea class="input-custom expanding" placeholder="Mensagem" rows="1" name="edtMensagem" id="edtMensagem"></textarea>
</div>
<div class="input-group text-right">
<button type="submit" id="btnEnviar" name="btnEnviar" class="submit progress-button" data-style="rotate-angle-bottom" data-perspective data-horizontal>Enviar</button>
</div>
</form>
And here the validation (original code, as it was when I took over the project, without my attempts):
<script>
$(document).ready(function(e) {
$("button#btnEnviar").click(function(e) {
var nome = $("#edtNome").val();
var mail = $("#edtEmail").val();
var fone = $("#edtTelefone").val();
var mensagem = $("#edtMensagem").val();
$.ajax({
type: 'POST',
url: "envia_mail_a2.php",
//context: document.body,
//dataType: 'text',
data: "nome="+nome+"&mail="+mail+"&fone="+fone+"&mensagem="+mensagem,
success: function(){
//alert('Enviado com sucesso')
setInterval(function(){
$("#edtNome").val('');
$("#edtEmail").val('');
$("#edtTelefone").val('');
$("#edtMensagem").val('');
}, 3000);
},
error: function () {
alert('Erro ao enviar');
}
});
});
});
</script>
Once again, thanks for all the attention
After looking at the code on the page, when calling new ProgressButton, there are two parameters passed to the constructor ... the button HTMLElement that will be turned into a progress button via the plugin, and a callback function that will determine what happens when the newly created progress button is clicked. Right now you have two click handlers on the progress button. One that is being passed into the new ProgressButton() call, and another one that you've pasted above that is created when the document is ready. The one being passed into the ProgressButton constructor is handling the animation of the button, and the additional click handler you've pasted above is taking care of validation. You need to move the validation code into the click handler that is being passed to the ProgressButton constructor so that the animation happens in-sync with validation. For instance, you could trigger the animation as the result of a success return from the validation service, or you could do something else to the button if there is an error. But all this should happen from a single handler since the validation is happening asynchronously, and right now, since the animation and validation are happening from two different handlers that are both triggered by clicks on the button, you're not able to sync those two processes up.
So I'm thinking something like this:
new ProgressButton( bttn, {
callback : function( instance ) {
var nome = $("#edtNome").val();
var mail = $("#edtEmail").val();
var fone = $("#edtTelefone").val();
var mensagem = $("#edtMensagem").val();
var animation = function() {
var progress = 0,
interval = setInterval( function() {
progress = Math.min( progress + Math.random() * 0.1, 1 );
instance._setProgress( progress );
if( progress === 1 ) {
instance._stop(1);
clearInterval( interval );
}
}, 200 );
}
$.ajax({
type: 'POST',
url: "envia_mail_a2.php",
//context: document.body,
//dataType: 'text',
data:"nome="+nome+"&mail="+mail+"&fone="+fone+"&mensagem="+mensagem,
success: function(){
//alert('Enviado com sucesso')
//call the animation
animation();
},
error: function () {
alert('Erro ao enviar');
//do another animation if there is an error
}
});
});
}
} );
To be honest, progress bars aren't great for AJAX calls when you're not able to really tell what the "progress" of the call is ... I guess you could do something that worked off the readyState of the XHR object using onreadystatechange events, but often times most AJAX progress indicators like this are some type of looping animation.

ng-show/ng-hide loops when a "submit()" added, making the browser crash

I am trying to add an error message with an either ng-show or ng-hide.
<p ng-show="submit()">Incorrect login/password.</p>
<form method="POST" name="adminform" ng-submit="submit()" class="admin-login-form">
<label for="username">Admin Login</label>
<input ng-model="username" type="text" name="username" class="form-control" required autofocus="yes"/>
<label for="password">Password</label>
<input ng-model="password" type="password" name="password" class="form-control" required />
<input type="submit" class="form-control" name="submit" value="Login" required/>
</form>
Ideally, the show/hide needs to be activated when submit() was run and did not succeed on login. However, when I do ng-show="submit()" it works but keeps refreshing itself and looping, making the browser crash and giving an error in the console even if the submit button itself hasn't been clicked.
$scope.submit = function() {
var data = {
'username': $scope.username,
'password': $scope.password
};
var hookphp = loginService.login();
hookphp.save(data,
function(result){
$location.path("dashboard");
},
function(){
alert('Invalid password/login.');
}
);
};
Also, it never gives me the alert when the login is not successful. Could anyone suggest how to do this properly? I am still in the process of figuring out how Javascript and Angular work. Thanks a lot!
<p ng-show="errorVisible">Incorrect login/password.</p>
In angular
$scope.errorVisible = true/false (set it whenever you need it)
So:
$scope.errorVisible = false;
$scope.submit = function() {
var data = {
'username': $scope.username,
'password': $scope.password
};
var hookphp = loginService.login();
hookphp.save(data,
function(result){
$location.path("dashboard");
$scope.errorVisible = false; //optional
},
function(){
$scope.errorVisible = true;
}
);
};
Also the reason it's looping forever in your initial code is that ng-show keeps calling the function, but the function doesn't return anything.
On your code, it seems like your function is not returning either true or false depending on the login status, so in that case, since function call is success, the output of the function will always be true causing your login failure label will be visible at all times.
As #MrVentzi suggested, it is better to use separate scope variable in order to decide wheter to show the message or not. If you try to do it as
<p ng-show="submit()">Incorrect login/password.</p>
ng-show will be constantly calling and listening to output of the function. In order to show you better, I created this example: http://jsfiddle.net/eytt2d8x/

How to submit a form with specific fieldset

I have a form like this:
<form name="paymentForm" id="paymentForm" action="/submit.jsp" method="post">
<fieldset id="ccData">
<input id="ccNumber" name="ccNumber"/>
</fieldset>
<fieldset id="otherData">
<input id="requestId" name="requestId"/>
</fieldset>
</form>
When you slick submit, I would like to submit(via ajax) only #ccData filedset to some different url (e.g. submitCC.jsp) and based on response I want to submit full form to actual url.
How can I achieve that ?
Use jQuery's serialize method
var formData = $("#ccData").serialize()​;
$.post("TheUrl",formData);
You could do that with JavaScript - e.g jQuery. You build an eventHandler like
$('#paymentForm').on('click', function () {
$(this).preventDefault();
if ($(this).hasClass('first_send')) {
$.ajax({
url: "your_url",
data: { ccData: $('#ccData').val()}
}).done(function ( data ) {
$('#paymentForm').addClass('first_send')
// examin the data, insert stuff you need and send the form again
// with ajax
})
} else {
$(this).removeClass('first_send')
// this is the second send - so do stuff here - show a result or so
}
})
With the class first_send you can check if it is the first send or the second. This is just an untested, incomplete idea how you could do it. I guess you get the big picture ...

Categories

Resources