$(document).ready(function() {
var login = $("#login").val();
var password = $('#password').val();
$('.login-button').click(function() {
alert(login);
});
});
HTML
<form method="post" class="login"> <p id="login-error"></p>
<p>
<label for="login">Username:</label>
<input type="text" name="login" id="login" placeholder="username">
</p>
<p>
<label for="password">Password:</label>
<input type="password" name="password" id="password" placeholder="password">
</p>
<p class="login-submit">
<button class="login-button">Login</button>
</p>
<p class="forgot-password">Fill your username and password.</p> </form>
It shows nothing! What's up with it? Any solution? The id names are correct
EDIT:
I have another problem. Dont want to open another question for that. I'm trying to get ajax answer from validate.php (it is in /views/admin/validate.php - it runs when opening domain.com/validate)
$(document).ready(function() {
$('.login-button').click(function() {
var login = $("#login").val();
var password = $('#password').val();
$.ajax({
type: 'POST',
url: '/view/admin/validate.php',
data: {
login : login,
password : password
},
success: function(data){
$('#login-error').html(data);
}
});
});
});
validate.php
<?php
session_start();
$user = mysql_real_escape_string($_POST['login']);
$password = mysql_real_escape_string(sha1($_POST['password']));
$query = mysql_query("SELECT * FROM `users` WHERE name = '$user' AND pass = '$password' AND privileges = 'superuser'");
$num_rows = mysql_num_rows($query);
if($num_rows == '0') {
echo "Username and Password are incorrect! (Maybe you don't have permission!)";
}
elseif($num_rows == '1') {
$expire = time()*60*60*60*60;
setcookie("user","$user",$expire);
$_SESSION['user'] = $user;
include '/views/admin/admin.php';
}
?>
It should return Username and Password are incorrect! (Maybe you don't have permission!) - but it doesn't.. Any solution??
var login = $("#login").val();
When this line runs, the input is empty.
You need to get the value after the user types something.
$('.login-button').click(function() {
var login = $('#login').val();
alert(login);
});
Try it :
$('.login-button').click(function() {
alert($("#login").val());
});
or :
$('.login-button').click(function() {
var login = $("#login").val();
alert(login);
});
or :
var login = "";
$('.login-button').click(function() {
login = $("#login").val();
alert(login);
});
Related
I am very new to PHP and JavaScript and I have made a PHP and Javascript login script. However, it just shoots out Incorrect username or password. even though it's correct. Here are my scripts:
PHP:
<?php
header('Access-Control-Allow-Origin: *');
$username = $_POST['username'];
$password = $_POST['password'];
if($username == "axqua" && $password == "abc")
{
$loggedin = true;
echo "Logged in as axqua";
}
else
{
$loggedin = false;
echo "Incorrect username or password.";
}
?>
Javascript:
<script>
var username = document.getElementById("usernameform").value.toString();
var password = document.getElementById("passwordform").value.toString();
var formData = {'username':username, 'password':password}
function posttourl() {
var posts = $.ajax({
'url': 'http://example.com/',
'type': 'POST',
'data': formData
})
posts.done(function (res) {
console.log(res)
})
}
</script>
HTML:
<p class="text">Username</p>
<input class="inputstyle" maxlength="12" id="usernameform">
<br>
<p class="text">Password</p>
<input class="inputstyle" type="password" maxlength="16" id="passwordform">
<br>
Login
I do not see a problem with this so I am not sure what is going on but if you can help then please do.
As confirmed by the comment, this is because the JS section run before the user entered the text (likely on page load), so
var username = document.getElementById("usernameform").value.toString();
var password = document.getElementById("passwordform").value.toString();
var formData = {'username':username, 'password':password}
are executed when the text boxes are empty, ignoring later input. Moving them into posttourl() ensure the values taken are current.
I'm new at ajax and i am confused becouse i think my ajax file is not sending data to php file or php is not getting it, IDK, Help me please
This is the form
<form id="register-form" method="post" role="form" style="display: none;">
<div class="form-group">
<input type="text" name="username" id="username" tabindex="1" class="form-control" placeholder="Username" value="">
</div>
<div class="form-group">
<input type="text" name="email" id="email" tabindex="1" class="form-control" placeholder="Email Address" value="">
</div>
<div class="form-group">
<input type="password" name="password" id="password" tabindex="2" class="form-control" placeholder="Password">
</div>
<div class="form-group">
<input type="password" name="confirm-password" id="confirm-password" tabindex="2" class="form-control" placeholder="Confirm Password">
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
<input type="submit" name="register-submit" id="register-submit" tabindex="4" class="form-control btn btn-register" value="Register Now">
</div>
</div>
</div>
</form>
This is the .js
$(document).ready(function(){
$("#register-submit").click(function(){
var email = $("#email").val();
var username = $("username").val();
var password = $("password").val();
$.ajax({
type: "POST",
url: "register.php",
data: "email="+email+"&username="+username+"&password="+password,
success:function(data){
alert("succes");
}
});
});
});
This is the .php
<?php
require_once("functions.php");
$email = $_POST["email"];
$username $_POST["username"];
$password $_POST["username"];
mysqli_query($connection, "INSERT INTO users(email, username, password) VALUES('$email', '$username', '$password')");?>
First of all:
var username = $("username").val();
var password = $("password").val();
Should be:
var username = $("#username").val();
var password = $("#password").val();
data: "email="+email+"&username="+username+"&password="+password
Should be:
data: {email: email, "username": username, password: password}
And
$username $_POST["username"];
$password $_POST["username"];
Should be:
$username = $_POST["username"];
$password = $_POST["password"];
You have to send the data in JSON format like:
var data = { "email": email, "username": username, "password": password };
so pass data var in data Ajax function!
1st: instead of using submit input click event you can use form submit event
$("#register-form").on('submit',function(){
and while you use a submit sure you need to prevent the page from default reload .. I think you problem is this point .. so you need to prevent the form by using e.preventDefault(); you can use it like
$("#register-form").on('submit',function(e){
e.preventDefault();
// rest of code here
$(document).ready(function(){
$("#submit").click(function(event) {
event.preventDefault();
var inputEmail = $("#email").val();
var inputUsername = $("#username").val();
var inputPassword = $("#password").val();
$.ajax({
type: "POST",
url: "register.php",
data: ({ email: inputEmail, password: inputPassword, username: inputUsername}),
success: function(data){
var obj = jQuery.parseJSON(data);
alert("Success " + obj.username + " " + obj.password + " "+ obj.email);
}
});
});
});
Here in .js file I put at the top in .click(function(event) { event.preventDefault(); }
preventDefault();
this function prevent the page from realoding when you press the submit button
data: ({ email: inputEmail, password: inputPassword, username: inputUsername})
Here i send the data data: ({nameOfTheVarieableYouWantToReadWithPHP: nameOfTheVariableFromJs})
Here is the .php file
require_once("database.php"); //require the connection to dabase
$email = protect($_POST['email']); //This will read the variables
$username = protect($_POST['username']); //sent from the .js file
$password = protect($_POST['password']); //
$result = array(); //This variable will be sent back to .js file
//check if the variables are emtpy
if(!empty($email) && !empty($username) && !empty($password)){
//db_query is my function from database.php but you can use mysqli_query($connectionVariable, $sqlString);
db_query("INSERT INTO users (email, username, password) VALUES ('$email','$username','$password')"); //Here insert data to database
//we will set array variables
$result['username'] = $username; //Here we set the username variable fron the array to username variable from js
$result['password'] = $password; // the password same as the username
$result['email'] = $email; //the email same as the username and password
}else{ // if the variables are empty set the array to this string
$result = "bad";
}
echo json_encode($result); //transform the result variable to json
In the .js file
success: function(data){
var obj = jQuery.parseJSON(data); //create a variable and parse the json from the php file
//You can set the variables get from the json
var usernameFromPhp = obj.username;
var passwordFromPhp = obj.password;
var emailFromPhp = obj.email;
alert("Success " + usernameFromPhp + " " + passwordFromPhp + " "+ emailFromPhp);//
}
So after validating the form via Jquery, I like to know if the username and password are valid. If they are, it should redirect to another page, else I want to find a way of showing it to the user. At this point, I'm really confused. Here's the jquery code:
$(document).ready(function(e) {
$('.error').hide();
$('#staffLogin').submit(function(e) {
e.preventDefault();
$('.error').hide();
uName = $('#staff_username').val();
pWord = $('#staff_password').val();
if(uName == ''){
$('#u_error').fadeIn();
$('#staff_username').focus();
return false;
}
if(pWord == ''){
$('#p_error').fadeIn();
$('#staff_password').focus();
return false;
}
$.ajax({
type : 'POST', url : 'staff_access.php', data : 'uName='+uName+'&pWord='+pWord,
success: function(html){
if(html == 'true'){
window.location = 'staff_page.php';
}
else{
$('#val_error').fadeIn();
}
}
})
});
});
PHP:
<?php
include('admin/config.php');
$username = $_POST['uName'];
$password = $_POST['pWord'];
$conn = mysqli_connect(DB_DSN,DB_USERNAME,DB_PASSWORD,dbname);
if ($conn) {
$qry = "SELECT lastname, firstname, FROM staff_user WHERE username='".$username."' AND pass='".$password."";
$res = mysqli_query($qry);
$num_row = mysqli_num_rows($res);
$row=mysql_fetch_assoc($res);
if ($num_row == 1) {
session_start();
$_SESSION['login'] = true;
$_SESSION['lastname'] = $row['lastname'];
$_SESSION['firstname'] = $row['firstname'];
$_SESSION['username'] = $row['username'];
echo "true";
}
else{
echo "false";
}
}
else{
$conn_err = "Could not connect.".mysql_error();
}
mysqli_close($conn);
?>
FORM:
<form name="staff_login" method="post" action="" id="staffLogin">
<fieldset>
<legend>Staff Login</legend>
<span class="fa fa-user fa-5x"></span>
<br><br>
<input type="text" name="staff_username" id="staff_username" placeholder="Username">
<br><span class="error" id="u_error">Username Required</span><br>
<input type="password" name="staff_password" id="staff_password" placeholder="Password">
<br><span class="error" id="p_error">Password Required</span><br>
<span class="error" id="val_error">Incorrect Username and Password combination</span>
<input type="submit" name="staff_login" value="Login">
</fieldset>
</form>
Your ajax data is sent in wrong format. POST data should be sent as an object.
$.ajax({
type : 'POST',
url : 'staff_access.php',
data : {
uName: uName,
pWord: pWord
},
dataType: 'text',
success: function(html){
if(html == 'true'){
window.location = 'staff_page.php';
}
else{
$('#val_error').fadeIn();
}
}
});
Also avoid using texts like 'html'. You may end up getting unnecessary errors due to that.
Use more relevant words like "success: function(response)"
Try to define a dataTpe in your ajax config - dataType: "html"
I'm trying to validate if a username is already taking or not. This onchange of an input field. I already got other checks but they don't work anymore since I added the ajax call. I'm new to ajax and javascript so the error can be there.
the html form:
<form action="test" method="post">
<input id="username" type="text" placeholder="Gebruikersnaam" name="username" required onchange="checkUserName()">
<br>
<input id="email" type="text" placeholder="Email" name="email" required onchange="validateEmail()">
<br>
<input id="pass1" type="password" placeholder="Type wachtwoord" name="password1" required>
<br>
<input id="pass2" type="password" placeholder="Bevestig wachtwoord" name="password2" required onchange="passwordCheck()">
<br>
<select name="typeAccount">
<option value="bedrijf">Bedrijf</option>
<option value="recruiter">Recruiter</option>
<option value="werkzoekende">Talent zoekt job</option>
</select>
<p id="demo1">
</P>
<p id="demo2">
</P>
<button type="submit">Scrijf mij in!</button>
</form>
the javascript that I use:
<script src="jquery.js">
function passwordCheck(){
var password1 = document.getElementById('pass1').value;
var password2 = document.getElementById('pass2').value;
if(password1 !== password2){
document.getElementById("pass1").style.borderColor = "#ff3333";
document.getElementById("pass2").style.borderColor = "#ff3333";
}else{
document.getElementById("pass1").style.borderColor = "#1aff1a";
document.getElementById("pass2").style.borderColor = "#1aff1a";
}
}
function validate(email){
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function validateEmail(){
var email = document.getElementById('email').value;
if(validate(email)){
document.getElementById("email").style.borderColor = "#1aff1a";
}else{
document.getElementById("email").style.borderColor = "#ff3333";
}
}
function checkUserName(){
var username = document.getElementById('username').value;
if(username === ""){
document.getElementById("username").style.borderColor = "#ff3333";
}else{
$.ajax({
url: "userCheck.php",
data: { action : username },
succes: function(result){
if(result === 1){
document.getElementById("username").style.borderColor = "#1aff1a";
}else{
document.getElementById("username").style.borderColor = "#ff3333";
}
}
});
}
}
</script>
The php script I use this is in a different file:
<?php
include("connect.php");
$connect = new Connect();
$username = mysql_real_escape_string($_POST['username']);
$result = mysql_query('select username from usermaindata where username = "'. $username .'"');
if(mysql_num_rows($result)>0){
echo 0;
}else{
echo 1;
}
?>
The script and the html form is in the same html-file and the php is in a seperate PHP-file.
I just want to check if the name is already in the database or not.
I assume your database connection is perfect.
$username = mysql_real_escape_string($_POST['username']);
change above code to
$username = mysqli_real_escape_string($db_connection,$_REQUEST['action']);
because in your ajax you're doing like
$.ajax({
url: "userCheck.php",
data: { action : username },
succes: function(result){
if(result === 1){
document.getElementById("username").style.borderColor = "#1aff1a";
}else{
document.getElementById("username").style.borderColor = "#ff3333";
}
}
});
You have not specified request type and you're fetching value using $_POST with different variable name username which is actually value
You should use $_REQUEST['action']
And make sure you've added jquery.js file in your html.
I am trying to learn from an example from online,for a login form with php and jquery and i am using the exactly the same example, but for some reason the AJAX isnt getting anything back but redirecting my to another php.
Here is a link of what i had been trying and the problem.
http://rentaid.info/Bootstraptest/testlogin.html
It supposed to get the result and display it back on the same page, but it is redirecting me to another blank php with the result on it.
Thanks for your time, i provided all the codes that i have, i hope the question isnt too stupid.
HTML code:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<form id= "loginform" class="form-horizontal" action='http://rentaid.info/Bootstraptest/agentlogin.php' method='POST'>
<p id="result"></p>
<!-- Sign In Form -->
<input required="" id="userid" name="username" type="text" class="form-control" placeholder="Registered Email" class="input-medium" required="">
<input required="" id="passwordinput" name="password" class="form-control" type="password" placeholder="Password" class="input-medium">
<!-- Button -->
<button id="signinbutton" name="signin" class="btn btn-success" style="width:100px;">Sign In</button>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javasript" src="http://rentaid.info/Bootstraptest/test.js"></script>
</body>
</html>
Javascript
$("button#signinbutton").click(function() {
if ($("#username").val() == "" || $("#password").val() == "") {
$("p#result).html("Please enter both userna");
} else {
$.post($("#loginform").attr("action"), $("#loginform:input").serializeArray(), function(data) {
$("p#result").html(data);
});
$("#loginform").submit(function() {
return false;
});
}
});
php
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
ob_start();
session_start();
include 'connect.php';
//get form data
$username = addslashes(strip_tags($_POST['username']));
$password = addslashes(strip_tags($_POST['password']));
$password1 = mysqli_real_escape_string($con, $password);
$username = mysqli_real_escape_string($con, $username);
if (!$username || !$password) {
$no = "Please enter name and password";
echo ($no);
} else {
//log in
$login = mysqli_query($con, "SELECT * FROM Agent WHERE username='$username'")or die(mysqli_error());
if (mysqli_num_rows($login) == 0)
echo "No such user";
else {
while ($login_row = mysqli_fetch_assoc($login)) {
//get database password
$password_db = $login_row['password'];
//encrypt form password
$password1 = md5($password1);
//check password
if ($password1 != $password_db)
echo "Incorrect Password";
else {
//assign session
$_SESSION['username'] = $username;
$_SESSION['password'] = $password1;
header("Location: http://rentaid.info/Bootstraptest/aboutus.html");
}
}
}
}
?>
Edit
$("button#signinbutton").click(function(){
if($("#username").val() ==""||$("#password").val()=="")
$("p#result).html("Please enter both userna");
else
$.post ($("#loginform").attr("action"),
$("#loginform:input").serializeArray(),
function(data) {
$("p#result).html(data); });
});
$("#loginform").submit(function(){
return false;
});
First of all, Remove :-
header("Location: http://rentaid.info/Bootstraptest/aboutus.html");
and if you want to display the data, echo username and password.
$_SESSION['username'] = $username;
$_SESSION['password'] = $password1;
echo $username."<br>".;
echo $password1;
The reason you are being redirected is that you are also calling $.submit. The classic form submit will redirect you to a new page, which is exactly what you don't want when you're using AJAX. If you remove this call:
$("#loginform").submit(function() {
return false;
});
you probably should have working solution. If not, let me know :)
Modify your javascript section so that
$("button#signinbutton").click(function() {
if ($("#username").val() == "" || $("#password").val() == "") {
$("p#result).html("Please enter both userna");
} else {
$.post($("#loginform").attr("action"), $("#loginform:input").serializeArray(), function(data) {
$("p#result").html(data);
});
}
});
$("#loginform").submit(function() {
return false;
});
is outside the function call.