i want check in my mysql database if the user enter the username and password correctly and then go in the home.html, i have some javascript code that detect when the user click the login button, but i can't understand how check in the database with javascript, i know how do that in php, but i can't understand how call the php from the javascript or do it directly in the js code, this is some code:
the form in the html:
<div id="password">
<div class="input username"><input type="text" placeholder="User name" /></div>
<div class="input password"><input type="password" placeholder="Password" /></div>
<button>Log in</button>
Back
</div>
</div>
then in my Login.js file i have this:
function forgot() {
//Se ho scritto la password allora fai l'animazione wobble, altrimenti vai in home.html
if($("#password .input.password input").attr("value")!='') {
$.notification(
{
title: "Wrong password",
content: "Just leave the password field empty to log in.",
icon: "!"
}
);
$("#password").removeClass().addClass("animated wobble").delay(1000).queue(function(){
$(this).removeClass();
$(this).clearQueue();
});
$("#password .input.password input").attr("value", "").focus();
} else {
document.location.href = "home.html";
}
}
now for the login i detect only if the field are empty, but i want detect mysql database how i can check it? because i want if the user enter wrong username and password span a $notification alert, anyone can help me?
Please suppose your html form is like below:
<input id="uname" name="uname" type="text" placeholder="User name" />
<input id="pass" name="pass" type="password" placeholder="Password" />
<button id="btn_login">Log in</button>
And suppose php script named checkPassword.php is like below:
<?php
/*
1.Retrieve post data : "uname" and "pass".
2.Cehck if user name and password is valid.
*/
if( /* valid user name and password */ ){
echo "OK";
}else{
echo "NG";
}
?>
The Javascript code could goes like below:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script language="javascript">
$(function() {
// set a event handler to the button
$("#btn_login").click(function() {
// retrieve form data
var uname = $("#uname").val();
var pass = $("#pass").val();
// send form data to the server side php script.
$.ajax({
type: "POST",
url: "checkPassword.php",
data: { uname:uname, pass:pass }
}).done(function( data ) {
// Now the output from PHP is set to 'data'.
// Check if the 'data' contains 'OK' or 'NG'
if (data.indexOf("OK") >= 0){
// you can do something here
alert("Login Successed.");
location.href = "ok.html";
}else if(data.indexOf("NG") >= 0){
// you can do something here
alert("Login Faild.");
location.href = "ng.html";
}
});
});
});
</script>
You can't communicate directly from client side JS to a server side database.
To make an HTTP request (to a server side program), use the XMLHttpRequest object.
if(document.pressed=='SUBMIT')
{
var uname = document.getElementById('uname').value;
if(uname.trim()=='' || uname.trim()==null)
{
alert("<?php echo 'uname_null'?>");
return false;
}
}
you can do the validation part on the sql server side if you use stored procedures
Related
I'm using $.ajax to submit my data to a PHP page and I know I can do a redirect when success response is returned. However, is there a way to execute a redirect from my PHP page where I post to?
PHP
If you want a PHP way you can set the header.
header('Location: www.example.com');
Warning you can only use header if you haven't sent any other information to the client.
Remember that header() must be called before any actual output is
sent, either by normal HTML tags, blank lines in a file, or from PHP.
It is a very common error to read code with include, or require,
functions, or another file access function, and have spaces or empty
lines that are output before header() is called. The same problem
exists when using a single PHP/HTML file.
Javascript
You can redirect the browser using the following:
window.location = "www.example.com";
This can be done at any time.
Sources: PHP-Header JS-Window-Location
Here is what you want. The code below post data to server php backend via ajax and redirect users if posted data is not
empty
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#signin').click(function(){
var username = $('#username').val();
var password = $('#password').val();
if(username==""){
alert('please Enter username');
}
else if(password==""){
alert('please Enter password');
}
else{
$('#loader').fadeIn(400).html('<span>Please Wait, User is being logged</span>');
var datasend = "username="+ username + "&password=" + password;
$.ajax({
type:'POST',
url:'login.php',
data:datasend,
crossDomain: true,
cache:false,
success:function(msg){
//empty username and password box after submission
$('#username').val('');
$('#password').val('');
$('#loader').hide();
$('#result').fadeIn('slow').prepend(msg);
$('#fadeoutResult').delay(5000).fadeOut('slow');
}
});
}
})
});
</script>
<input
name="username"
type="text"
class="form-control input-lg"
id="username"
/>
<input
name="password"
type="password"
class="form-control input-lg"
id="password"
/>
<div id="loader"></div>
<div id="result"></div>
<button type="submit" id="signin">
Submit
</button>
test.php
<?php
// lets do redirect if username and password is not empty. you can apply the same principle is your submission is successful
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
if ($username != '' && $password !=''){
header('Location: success.php');
exit();
}
?>
I am trying to create on-page login.
without ajax it works very well. Here is my login.php;
if($_POST)
{
$username =$_POST["username"];
$password =$_POST["password"];
$query = $handler->query("SELECT * FROM members WHERE username='$username' && password='$password'",PDO::FETCH_ASSOC);
if ( $say = $query -> rowCount() ){
if( $say > 0 ){
session_start();
$_SESSION['session']=true;
$_SESSION['username']=$username;
$_SESSION['password']=$password;
echo "ok";
}else{
echo "Couldn't login.";
}
}else{
echo "Wrong username or password.";
}
}
Anyway, here is my java script code;
$(function(){
$("#loginbutton").click(function(){
var username = $("#username").val();
var password = $("#password").val();
if(username != "" && password != ""){
$.ajax("login.php",{
type : "POST",
data : "username="+username+"&password="+password,
success : function(data){
if(data == "ok"){
$("#message").html(data);
}else{
$("#fail").fadeIn();
}
}
});
}
});
});
Even though I put correct login information (when I get "ok" response from login.php, it always outputs $("#fail").fadeIn(); . instead of $("#message").html(data); I couldn't figure out where I am mistaken.
and here is login form:
<div id="login">
<form action="" onsubmit="return false;" method="post">
<input type="text" class="form-control" id="username" name="username" placeholder="Username" autocomplete="off"><br>
<input type="password" class="form-control" id="password" name="password" placeholder="Password" autocomplete="off"><br>
<input class="btn btn-success" type="submit" id="loginbutton" value="Login">
</form>
<div id="message"> </div>
<div id="fail" style="display: none;">failed.</div>
</div>
You are using type as post, but sending parameters as get.Change your ajax like this,
$.ajax("login.php",{
type : "POST",
data : {username:username,password:password},// only this line is changed.
success : function(data){
if(data == "ok"){
$("#message").html(data);
}else{
$("#fail").fadeIn();
}
}
});
Here is a quick example of using post with JQuery AJAX.
$(document).ready(function(){
$.post("login.php", {username:username, password:password}, function(data){
if(data == 'ok'){
$("#message").html(data);
}else{
alert(data);//alert the data you receive. It alerts you if there is any error in php file.
$("#fail").fadeIn();
}
});
});
Hope that was helpful!
Firstly, debug your code like this:
1) On button click you will put alert function inside javascript code. if it is working then move second step.
2) use alert function to print username and password if it comes inside your javascript code and correct as you put into input fields then move third step.
3) use serialize method in javascript.
I hope its help you to get your solution.
fairly new to the language, i have created a simple login system and i am attempting to submit the forms without page refreshes. I have completely created the registration system without page refresh ( coupled with dynamic username checking) and am now attempting to convert the actual login form as well, so that the user can be displayed as logged in without page refresh.
I attempted to use the same method, however now i need to pass both username and password to the validation script, and i am unable to get the password part to work for some reason... although username works fine.
I have it set up to display one error if the password is validated successfully and the other if it is not.. i may be overthinking it, i appreciate your assistance in this possibly trivial problem
PS first go with stack so please point out any suggestions to formatting etc
PHP
<?php
require_once('startsession.php');
$page_title = 'Log In';
require_once('header.php');
require_once('connectvars.php');
require_once('navmenu.php');
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="invisiblelogin.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.error').hide();
$('#Info').hide();
});
function check_login(){
var username = $("#username").val();
var password = $("#password").val();
if(username.length > 0 && password.length > 0){
$.post("logincheck.php", {
username: $('#username').val(),
password: $('#password').val(),
}, function(response){
setTimeout("finishAjax('Info', '"+escape(response)+"')", 450);
});
return false;
}
}
function finishAjax(id, response){
//showing of errors is just visually showing me whether or not the password validation worked
$('#'+id).html(unescape(response));
var valid = $("#Info").html();
if( valid > 0) {
$("label#username_error2").show();
}
else {
$("label#password_error").show();
}
}
</script>
<div id="contact_form">
<form action="" name="contact">
<fieldset><legend>Log In Info</legend>
<font color="red"><div id="Info"></div></font>
<table>
<tr><td><label for="username" id="username_label">Username:</label>
<input type="text" id="username" name="username" value="" class="text-input" /></td>
<td><label class="error" for="username" id="username_error2">Enter your username. </label></td></tr>
<tr><td><label for="password" id="password_label">Password:</label>
<input type="password" id="password" name="password" value="" class="text-input" /> </td>
<td><label class="error" for="password" id="password_error">Enter your password. </label></td></tr></table>
<input type="submit" name="submit" class="button" id="submit_btn" value="Sign Up" onclick="return check_login();" />
</fieldset>
</form>
</div>
<?php
// Insert the page footer
require_once('footer.php');
?>
JS
$(function() {
$('.error').hide();
$(".button").click(function() {
// validate and process form here
$('.error').hide();
var username = $("input#username").val();
var password = $("input#password").val();
if (username == "" || password == "") {
if (username == "") {
$("label#username_error2").show();
$("input#username").focus();
}
if (password == "") {
$("label#password_error").show();
$("input#password").focus();
}
return false;
}
return false;
});
});
Intermediate PHP
<?php
require_once('connectvars.php');
if($_REQUEST)
{
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) or die (mysqli_error());
$username = mysqli_real_escape_string($dbc, trim($_REQUEST['username']));
$password = mysqli_real_escape_string($dbc, trim($_REQUEST['password']));
$query = "SELECT * FROM login_info WHERE username = 'username' AND password = SHA('$password')";
// ------------ THIS PASSWORD PART DOES NOT READ CORRECTLY
$data = mysqli_query($dbc, $query);
if (mysqli_num_rows($data) > 0) {
echo '1';
}
else {
echo '0';
}
}
?>
Ok.. a Few things...
I think you need to troubleshoot the 2 things it could really be... 1) Is the correct value being passed through to the PHP Page? You can check this in the CONSOLE of firebug (an extension for firefox that every developer should have). 2) Is your actual password validation working OK? Hard-code the password. Use the die() function to output data in the PHP page. The result will be seen in firebug as well.
If you're using $.post() on the JS side, your PHP should use $_POST instead of $_REQUEST. Shouldn't impact anything notable, but just thought I would add that.
This code is a little worrying...
if( valid > 0) {
$("label#username_error2").show();
}else {
$("label#password_error").show();
}
Most likely, valid is a string, and will not parse '0' as 0. While a login script is a true/false (0/1) procedure, PHP pages that are called by an ajax function should always return some sort of structure. For example...
Change your POST to expect a json response.
$.post("logincheck.php", {
username: $('#username').val(),
password: $('#password').val(),
}, function(response){
setTimeout(function(){ //Note the change here.
finishAjax('Info', response); //Note the change here.
}, 450); //Note the change here.
}, 'json'); //Note the change here.
Then create a PHP function that will return a json package that your JS will use.
function SendJSONResponse($success, $msg=null, $additionalReturnData=null){
$result = array('success'=>$success);
if ($msg) $result['msg']=$msg;
if ($additionalReturnData) $result=array_merge($reult, $additionalReturnData);
die(json_encode($result));
}
Once you have that, your login script should look more like
if (mysqli_num_rows($data) > 0) {
SendJSONResponse(
true,
null,
array('data'=>$data) //Pass the logged in users info for use in JS
);
}else {
SendJSONResponse(false, 'Username or Password not found');
}
and your JS would look like this...
function finishAjax(id, response){
if( response.success) {
alert('logged in as ' + response.data.full_name + ' (' + response.data.email + ')');
$("label#username_error2").show();
}else {
alert(response.msg);
$("label#password_error").show();
}
}
Im building a login/register system using javascript to show particular divs for the system e.g
1st div = menu option to either login or register
2nd div = depending on what was clicked (login or register) shows login form or register form
3rd div = shows when user has successfully registered/logged in
the script looks like this:
html:
<article id="container">
<div id="load-new" class="game_menu">
<h1>LOAD/NEW</h1>
<button id="new_but" type="button">New Game</button>
<button id="load_but" type="button">Load Game</button>
</div>
<div id="reg" class="game_menu">
<h1>REGISTER</h1>
<form name="register" method="post" action="">
<label for="usernamesignup" class="uname">Your username</label>
<input id="usernamesignup" name="usernamesignup" required="required" type="text" placeholder="Username" />
<label for="emailsignup" class="youmail"> Your email</label>
<input id="emailsignup" name="emailsignup" required="required" type="email" placeholder="domain#mydomain.com"/>
<label for="passwordsignup" class="youpasswd">Your password </label>
<input id="passwordsignup" name="passwordsignup" required="required" type="password"/>
<label for="passwordsignup_confirm" class="youpasswd">Please confirm your password </label>
<input id="passwordsignup_confirm" name="passwordsignup_confirm" required="required" type="password"/>
<button id="reg_submit" type="button">Register</button>
</form>
</div>
<div id="login" class="game_menu">
<h1>LOGIN</h1>
<form name="login" method="post" action="">
<label for="username" id="username_label">Username:</label>
<input type="text" name="username" id="username" value=""/>
<label for="password" id="password_label">Password:</label>
<input type="password" name="password" id="password" value=""/>
<button id="login_submit" type="button">Login</button>
</form>
</div>
<div id="access" class="game_menu">
<h1>ACCESS</h1>
<button id="login_but" type="button">Login</button>
<button id="reg_but" type="button">Register</button>
</div>
<canvas id="TBG" width="640" height="416">
Please use a more up to date browser
</canvas>
the javascript looks like this
main.js:
//----------Login/Register Gui --------------
$('#load-new').hide();
$('#reg').hide();
$('#login').hide();
//create new instance of gui class
var ui = new Gui();
//if login_but is clicked do ui.login function
$('#login_but').click(ui.login);
//if reg_but is clicked do ui.register function
$('#reg_but').click(ui.register);
//if login_sumbit button is clicked do ui.login_ajax function
$("#login_submit").click(ui.login_ajax);
$("#reg_submit").click(ui.register_ajax);
gui.js:
function Gui (){
var valid = 'true';
var invalid = 'false';
//hide access div, show login div
this.login = function()
{
$('#access').hide();
$('#login').show();
};
//hide access div, show register div
this.register = function()
{
$('#access').hide();
$('#reg').show();
};
//function to send login data to php script login.php
this.login_ajax = function()
{
//username user inputted
var username = $("#username").val();
//password user inputted
var password = $("#password").val();
//inputted data made into JSON string
var dataString = {"reg":invalid, "login":valid, "username":username ,
"password":password};
//AJAX Request to login.php
$.ajax({
type:"POST",
url:"PHP/class.ajax.php",
data: dataString,
dataType: 'JSON',
success: function(success) {
alert("Your are logged in");
if(success == 'true'){
$('#login').hide();
$('#load-new').show();
}
},
error: function(){
alert("ERROR in AJAX");
}
});
};
this.register_ajax = function()
{
var username_signup = $("#usernamesignup").val();
var email_signup = $("#emailsignup").val();
var password_signup = $("#passwordsignup").val();
var password_signup_confirm = $('#passwordsignup_confirm').val();
var dataString = {"reg":valid, "login":invalid, "username_signup":username_signup,
"email_signup":email_signup,
"password_signup":password_signup, "password_signup_confirm":password_signup_confirm};
$.ajax({
type:"POST",
url:"PHP/class.ajax.php",
data: dataString,
dataType: 'JSON',
success: function(success) {
alert("You are registered");
if(success == 'true'){
$('#reg').hide();
$()
$('#load-new').show();
}
},
error: function(){
alert("ERROR in AJAX");
}
});
}
}
i use ajax to send requests to php scripts to process login or register.
the script that the ajax requests is simple a go between so i can select specific functions in either the login php or register php.
i would like to have an are in my html to show if a user is logged in or not a bit like the are in the top right on the runescape website : here.
now i tried this php in my header.php file:
if(isset($_POST['username'])){
$is_logged_in = '<div id = "user_box">Welcome '.$_POST['username'].'</div>';
}
else
{
$is_logged_in = '<div id = "welcome_box">Welcome friend!</div>';
}
but obviously this wouldnt work because the page doesnt refresh where im using javascript to show different parts of the menu.
MY QUESTION:
What would be the most pratical way to achieving this effect with the javascript/php system i have in place?
Would i use javascript to hide/show divs like i have with the menu divs? or is there a function i can use to refresh the page without it sending me back to the first menu div?
Thanks for your time
Tom
Right now you are only sending back one value from the php scripts that you are calling using ajax, you are only using true for a successful login or registration.
What you could do, is modify these scripts to return multiple values. So apart from the true value for a successful login, you also send the username and then in your javascript you use that username to build a html block to show in the top area where you want to show the username.
You are already using json, so you only have to generate an array with return values in your php script and use echo json_encode($your_return_values); to send it to your javascript success variable.
By the way, you can use jquery / javascript to replace and build whole sections of your html, you don't need to put everything in at the start just to hide it.
If I'm understanding your question correctly your wanting to indicate to the user that they are logged in without reloading the page and by displaying a div in the top right corner.
That being the case you could create a hidden div with an absolute top right position which would be something like:
<div id="welcome" style="display:none; postion:absolute; top:0; float:right;">...</div>
In the 'success:' portion of the ajax request above, add a call to a new js function that makes a separate ajax request to retrieve a json object containing the logged in users display name and any other information that you want to show. Using that json data you could then populate 'welcome' div accordingly and change it's display to block.
I have two web pages which work basically the same, code-wise, but one of them does not seem to cache information. By 'cache', I mean on the client/browser side. The text field does not retain previously entered information. In the first example below, if you register and then log in, the next time you log in, your username will be cached in the the browser to be selected; while in the second example, it does not retain that info.
http://www.dixieandtheninjas.net/hunter/ has a login prompt. once you've logged in once from a browser, when you revisit the page it has cached your username.
http://www.dixieandtheninjas.net/dynasties/ also has a login prompt, but it does not cache! And I cannot figure out why.
Perhaps because the second one is not within FORM tags? Maybe there's some other tiny coding mistake I've made which causes this.
Here's the code from the first example:
<form method = "post"
action = "">
Username: <input type="text" name="login_name" value="" />
<br><br>
Password: <input type="password" name="password" value="" />
<br><br>
<input type="submit" value="Login" />
</form>
Here is code from the second example: Note that the clicks are handled by jquery in the second example, while the first just uses pure html and php
<p>
Email address: <input type="text" id="logininfo" value="" />
<br>
Password: <input type="password" id="password" value="" />
<br>
<input type="button" id="loginbutton" value="Login" />
</p>
Here is the jquery used in the second example:
<script type ="text/javascript">
$(function(){
$('#loginbutton').click(function(){
var loginvar = $('#logininfo').val();
var passvar = $('#password').val();
//alert(loginvar + ", " + passvar);
if (loginvar != '' && passvar != '') {
var subdata = {
logindata : loginvar,
passdata : passvar
};
$.ajax({
url: "index_backend.php",
type: 'POST',
data: subdata,
success: function(result) {
//alert(result);
if (result == '1') {
// success
window.location.replace("http://www.dixieandtheninjas.net/dynasties/playermenu.php")
} else if (result == '2') {
//$('#logininfo').empty();
$('#logininfo').attr('value', '')
$('#password').attr('value', '')
alert("Login failed. Please try again, or register if you have not already created an account.");
} else {
alert("Something has gone wrong!");
alert (result);
}
} // end success
}); // end ajax
} else {
alert ("Please enter a username and password.");
}
}); /// end click function for button
}); //// end
</script>
Since you aren't truly submitting the form in the jQuery one, the browser doesn't know that the user has attempted to use this as input vs just typed something in and then went to another page. Because of that, you won't be seeing it in the stored form data.