AJAX instant check with php and javascript - javascript

I am developing a little webiste where I need to handle User registration. As usual, if a user requests a username that is already being used, the system should not allow to proceed with the registration.
I want to verify that during the register as most modern websites do. How do I do that using AJAX?
Register form:
<div class="container">
<form id="register_form" action="actions/register_action.php" method="post">
<div class="form-group">
<label for="name_area">Name</label>
<input type="text" name="name" class="form-control" placeholder="Name">
</div>
<div class="form-group">
<label for="username_area">Username</label>
<input type="text" name="username" class="form-control" id="username_id" placeholder="Username">
</div>
<div class="form-group">
<label for="email_area">Email</label>
<input type="email" name="email" class="form-control" placeholder="Email">
</div>
<div class="form-group">
<label for="pass_area">Password</label>
<input type="password" name="pass" class="form-control" placeholder="Password">
</div>
<div class="form-group">
<label for="conf_pass_area">Confirm password</label>
<input type="password" name="conf_pass_area" class="form-control" placeholder="Confirm password">
</div>
<br>
<div class="form-group">
<input type="submit" class="btn btn-primary" id="button_area" placeholder="Submit">
<!--action to:register_action!-->
</div>
</div>
</form>
</div>
users.php (where I do my php function regarding users):
<?php
//checks if username inserted is already in use
function check_username($username_pretended) {
global $conn;
$stmt = $conn->prepare('SELECT * FROM CommonUsers WHERE username=?');
$stmt->execute(array($username_pretended));
$res = $stmt->fetch();
if($res['username'] == "") {
return false;
}
else return true;
}
//inserts an user in the database
function insertUser($name, $username, $email, $password) {
global $conn;
$stmt = $conn->prepare('INSERT INTO CommonUsers(name, username, email, password) VALUES (?, ?, ?, ?)');
$stmt->execute(array($name, $username, $email, $password));
}
?>

From top of my head:
$("#username_id").on("change", function()
{
$.ajax(
{
method: "get", // or maybe post?
url: "yoururlhere",
data:
{
username: $(this).val()
},
success: function(data)
{
if (data == "0")
{
// Hide warning
}
else
{
// Warn user that username is already taken
}
}
});
});
This is the most simple way of doing this. Its sending the username to a server url for checking. Of course you will need an element to show the warning(which I could not find in your DOM).
You can check the ajax() method docs for detailed options.
In your PHP file:
$username = $_GET["username"];
if (check_username($username))
{
return "1";
}
else
{
return "0";
}

Related

Has Post request a limited number of parameters?

I'm trying to send to my server 5 parameters:
Action: will contain the name of the form, in this case "signin"
Name: Name of the person who wants to signin
Surname: Surname of the person who wants to signin
Email: Email of the person who wants to signin
Password: Password of the person who wants to signin
the problem is that my server reads only 4 parameters: Name, Surname, Email and Password, and it don't see Action!
Here's the code:
Javascript:
function signin() {
alert("OK");
var action = $(this).attr('name'); // puts in action the name of the form (this case "signin")
$.ajax({
type: "POST",
url: "submit.php",
data: {
Action: action, // the server don't see it!!
Name: document.getElementById('signin-name').value, // Name in the form
Surname: document.getElementById('signin-surname').value, // // Surname in the form
Email: document.getElementById('singin-email').value, // Email in the form
Password: document.getElementById('singin-password').value // // Password in the form
},
cache: false,
success: function() {
alert("success");
window.location.href = "index.php"; // load the index.php page, which contains the login form
}
});
}
PHP - Signin.php:
<!-- Signin Form -->
<?php
require('include/header.php');
?>
<div class="limiter">
<div class="form-container">
<div class="form-wrap">
<form action="submit.php" method="post" name="form-signin" id="form-signin" autocomplete="off">
<span class="form-title">Registration form</span>
<div class="form-field">
<label for="Name">Name</label>
<input type="text" name="Name" id="signin-name" class="form-control" required pattern=".{1,100}" autofocus>
</div>
<div class="form-field">
<label for="Surname">Surname</label>
<input type="text" name="Surname" id="signin-surname" class="form-control" required pattern=".{1,100}" autofocus>
</div>
<div class="form-field">
<label for="email">Email address</label>
<input type="email" name="Email" id="signin-email" class="form-control" required>
</div>
<div class="form-field">
<label for="Password">New password</label>
<input type="password" name="Password" id="signin-password" placeholder="Almeno 6 caratteri" class="form-control">
</div>
<div id="display-error" class="alert alert-danger fade in"></div><!-- Display Error Container -->
<div class="form-submit-container">
<div class="form-submit-wrap">
<button class="form-cancel-button" type="submit">Cancel</button>
<button class="form-submit-button" type="submit" onclick="signin()">Signin</button>
</div>
</div>
</form>
</div>
</div>
</div>
<?php require('include/footer.php');?>
PHP - Submit.php:
<?php
#Detect AJAX and POST request, if is empty exit
if((empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') or empty($_POST)){
exit("Unauthorized Acces");
}
require('inc/config.php');
require('inc/functions.php');
# Check if Login form is submitted
if(!empty($_POST) && $_POST['Action'] === 'form-login'){
# Define return variable. for further details see "output" function in functions.php
$Return = array('result'=>array(), 'error'=>'');
$email = $_POST['Email'];
$password = $_POST['Password'];
/* Server side PHP input validation */
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$Return['error'] = "Please enter a valid Email address.";
} else if($password === '') {
$Return['error'] = "Please enter Password.";
}
if($Return['error']!='') {
output($Return);
}
# Checking Email and Password existence in DB
# Selecting the email address of the user with the correct login credentials.
$query = $db->query("SELECT Email FROM USERS WHERE Email='$email' AND Password='$password'");
$result = $query->fetch(PDO::FETCH_ASSOC);
if($query->rowCount() == 1) {
# Success: Set session variables and redirect to Protected page
$Return['result'] = $_SESSION['UserData'] = $result;
} else {
# Failure: Set error message
$Return['error'] = 'Invalid Login Credential.';
}
output($Return);
}
# Check if Registration form is submitted
if(!empty($_POST) && $_POST['Action'] === 'form-signin') {
# Define return variable. for further details see "output" function in functions.php
$Return = array('result'=>array(), 'error'=>'');
$name = $_POST['Name'];
$surname = $_POST['Surname'];
$email = $_POST['Email'];
$password = $_POST['Password'];
# Server side PHP input validation
if($name === '') {
$Return['error'] = "Please enter Full name.";
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$Return['error'] = "Please enter a valid Email address.";
} else if($password === '') {
$Return['error'] = "Please enter Password.";
}
if($Return['error']!='') {
output($Return);
}
# Check Email existence in DB
$result = $db->query("SELECT Email FROM USERS WHERE Name='$name' AND Surname='$surname' AND Email='$email'");
if($result->rowCount() == 1){
# Email already exists: Set error message
$Return['error'] = 'You have already registered with us, please login.';
}else{
# Insert the new user data inside the DB
try{
$db->query("INSERT INTO `users` (`ID_user`, `Name`, `Surname`, `Email`, `Password`) VALUES (NULL, '$name', '$surname', '$email', '$password')");
}
catch (PDOException $e) {
echo $e->getMessage();
}
# Success: Set session variables and redirect to Protected page
$Return['result'] = $_SESSION['UserData'] = $result;
}
output($Return);
}
PHP - Functions.php
# Function to set JSON output
function output($Return=array()){
header('Content-Type: application/json; charset=UTF-8');
#exit(json_encode($Return)); # Final JSON response
echo json_encode($Return);
}
here is a screenshot of the debugger:
Debug Screenshot
function signin() {
alert("OK");
var action = $('#form-signin').attr('name'); // puts in action the name of the form (this case "signin")
// alert(action);
$.ajax({
type: "POST",
url: "submit.php",
data: {
Action: action, // the server don't see it!!
Name: $('signin-name').val(), // Name in the form
Surname: $('signin-surname').val(), // // Surname in the form
Email: $('singin-email').val(), // Email in the form
Password: $('singin-password').val() // // Password in the form
},
cache: false,
success: function() {
alert("success");
window.location.href = "index.php"; // load the index.php page, which contains the login form
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="limiter">
<div class="form-container">
<div class="form-wrap">
<form action="submit.php" method="post" name="form-signin" id="form-signin" autocomplete="off">
<span class="form-title">Registration form</span>
<div class="form-field">
<label for="Name">Name</label>
<input type="text" name="Name" id="signin-name" class="form-control" required pattern=".{1,100}" autofocus>
</div>
<div class="form-field">
<label for="Surname">Surname</label>
<input type="text" name="Surname" id="signin-surname" class="form-control" required pattern=".{1,100}" autofocus>
</div>
<div class="form-field">
<label for="email">Email address</label>
<input type="email" name="Email" id="signin-email" class="form-control" required>
</div>
<div class="form-field">
<label for="Password">New password</label>
<input type="password" name="Password" id="signin-password" placeholder="Almeno 6 caratteri" class="form-control">
</div>
<div id="display-error" class="alert alert-danger fade in"></div><!-- Display Error Container -->
<div class="form-submit-container">
<div class="form-submit-wrap">
<button class="form-cancel-button" type="submit">Cancel</button>
<button class="form-submit-button" type="submit" onclick="signin()">Signin</button>
</div>
</div>
</form>
</div>
</div>
</div>
The problem is with your scope for $this. Since your Javascript is called within a BUTTON element, $this has a scope relative to the button, not the form. In trying to check what $this returns by itself, it says [object Window].
function signin() {
console.log(this);
}
Console:
[object Window]
You need to either pass this via signin(this) and backtrack to the containing form element if you plan on reusing the Javascript for other forms or just use the form id in place of this.
HTML:
<button onclick="signin(this)">
JS:
function signin(element) {
var action = element.form.getAttribute("name");
}
or just simply change the this to the form's id as Lakmal pointed out:
function signin() {
var action = $("#form-signin").attr("name");
}

Ajax Login Response Error

i'm traying to login with ajax and php, in that situation i'm logging succesfuly actually. But i'm trying to make an alert and refresh the page when logged in.
When i attempt to login, its gives me error and no refreshing. But if i refresh the page, i see i have session in php. I don't understand why.
Here is my code;
<script>
$(document).ready(function(){
$('#login_btn').click(function(){
var email = $('#email').val();
var password = $('#password').val();
if(email == '' || password == ''){
$("#login_error").html("*** Please enter your email / password");
}else{
$('#login_error').html("<strong class='text-success'>Validating...</strong>");
$.ajax({
url: "login.php",
method: "post",
data:{email:email, password:password},
success: function(data){
if (data === 'yes') {
window.location.reload();
}else{
$('#login_error').html("<strong class='text-danger'>ERROR...</strong>");
}
}
});
}
});
});
</script>
login php:
<?php
session_start();
include ('../config/setup.php'); #database connection
if(isset($_POST['email'])){
$q = "SELECT * FROM users WHERE email = '$_POST[email]' AND password = '$_POST[password]'";
$r = mysqli_query($dbc, $q);
if(mysqli_num_rows($r) > 0){
$_SESSION['email'] = $_POST['email'];
echo "yes";
}else{
echo "no";
}
}
?>
Html: (Using login form inside a modal)
<div class="modal-body">
<div class="form-horizontal">
<div class="form-group">
<label for="email" class="col-sm-4 control-label">Email</label>
<div class="col-sm-8">
<input type="email" class="form-control" name="email" id="email" placeholder="Account Email">
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-4 control-label">Password</label>
<div class="col-sm-8">
<input type="password" class="form-control" name="password" id="password" placeholder="Account Password" >
</div>
</div>
<div class="form-group">
<div class="col-sm-1"></div>
<div align="center" class="col-sm-10">
<button name="login_btn" id="login_btn" class="btn btn-success btn-block text-center"><span id="loader_before" class="glyphicon glyphicon-log-in" aria-hidden="true"></span><i id="loader" class="fa fa-spinner fa-spin fa-x fa-fw"></i> Log in to Account</button>
</div>
<div class="col-sm-1"></div>
</div>
</div>
<div align="center" class="container-fluid">
<h6><strong class="text-danger">Forgot your password? Click here..</strong></h6>
</div>
<h5><div id="login_error" class="text-warning"></div></h5>
</div>
You just need to update your if block in response as below
`
if (data === 'yes') {
alert("You message here!");
window.location.reload();
}else{
$('#login_error').html("<strong class='text-danger'>ERROR...</strong>");
}
`
When you call echo on php, it will write the value, but not return it. That's the problem.
You are not returning "yes" or "no" from login.php, you're just doing echo, which will only write the value but not return it to the caller.
The ajax call is waiting for a response to process it with the 'success' callback. Since login.php is not returning anything, it will always fall into the else clause.
The solution is to change this on login.php
if(mysqli_num_rows($r) > 0){
$_SESSION['email'] = $_POST['email'];
return "yes";
}else{
return "no";
}

Ajax submit Form serialized data in php are null

I ve been searching all relative questions here and still cant figure out the problem I have.
I am using a simple modal form :
<p id="messages">Let's make today a great day!</p>
<form id="myloginform" name="myloginform" action="scripts/login.php" method="post" >
<div class="form-group">
<label for="username" class="">Enter username</label>
<input type="text" class="form-control input-lg c-square" id="username" name="username" placeholder="Username" required> </div>
<div class="form-group">
<label for="password" class="">Enter pass</label>
<input type="password" class="form-control input-lg c-square" id="password" name="password" placeholder="Password" required> </div>
<div class="form-group">
<div class="c-checkbox">
<input type="checkbox" id="login-rememberme" class="c-check">
<label for="login-rememberme" class="c-font-thin c-font-17">
<span></span>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn c-theme-btn btn-md c-btn-uppercase c-btn-bold c-btn-square c-btn-login" id="check">login</button>
</div>
</form>
I am using ajax to pass the form to a php file :
<script>
$(document).ready(function(){
$('form#myloginform').submit(function(e) {
var my_data = $('form#myloginform').serialize();
$.ajax({
type : 'POST',
url : 'scripts/login.php',
cache : false,
data : my_data,
contentType : false,
processData : false,
dataType: 'json',
success: function(response) {
//TARGET THE MESSAGES DIV IN THE MODAL
if(response.type == 'success') {
$('#messages').addClass('alert alert-success').text(response.message);
} else {
$('#messages').addClass('alert alert-danger').text(response.message);
}
}
});
e.preventDefault();
});
});
</script>
The login.php file is very simple and returns an json $output response
<?php
$username = $_POST['username'];
$password = $_POST['password'];
if($username == "Test"){
$success = true;
}
if($success == true) {
$output = json_encode(array('type'=>'success', 'message' => $username));
} else {
$output = json_encode(array('type'=>'error', 'message' => $username));
}
die($output);
?>
The $output in every case returns null. I checked with firebug, and everything is OK , no errors, POST perfect still I cannot get the variables in php to work. Any ideas ??? Is something wrong with my approach or do I need to deserialize the data in the php file , somehow...???
Don't use die.
Use echo or print.
Also set contentType to true.

Html form refuses to be submitted via JQuery

So I was following an AJAX/JQuery tutorial for a registration script that will be acted upon by PHP/MySQL and will be submitted via JQuery.
Now the problem that I'm encountering is that the form submits directly to the action page, which should not be so, as it supposed to submit to script.js Here are the html code for the form.
<form method="post" id="register-form" action="transact-user.php">
<h2 class="form-signin-heading"></h2>
<div class="form-group">
<div class='row'>
<div class='col-sm-6'>
<input type='text' class='form-control' id='fname' name='fname' placeholder="First name">
</div>
<div class='col-sm-6'>
<input type='text' class='form-control' id='lname' name='lname' placeholder="Last name">
</div>
</div>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Phone Number" name = "phone" id = "phone" >
</div>
<div class="form-group">
<input type="email" class="form-control" placeholder="Email address" name = "email" id ="email">
<span id="check-e"></span>
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="Password" name = "password" id = "password">
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="Password Again" name = "confirmpassword" id = "confirmpassword">
</div>
<div class="form-group">
<button class="btn btn-primary btn-block btn-apply" type="submit" name="btn-save" id = "btn-submit"><span class="glyphicon glyphicon-log-in"></span> Register</button>
</div>
</form>
</div> <!-- /container -->
<div id = "ack"></div>
script.js
$("button#btn-submit").click(function()
{ /* validation */
/* form submit */
if ($("fname").val()=="" || $("lname").val()=="" )
$("div#ack").html("Please enter both your first name and your surname");
else
$.post($("#register-form").attr("action"),
$("#register-form: input").serializeArray(),
function(data){
$("div#ack").html(data);
});
$("#register-form").submit(function(){
return false;
})
/* form submit */
});
Finally, this is the action php script transact-user.php
<?php
if($_POST)
{
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$password = $_POST['password'];
$confirmpassword = $_POST['confirmpassword'];
if($email != '') {
$qry = "SELECT * FROM users WHERE email='$email'";
$result = mysqli_query($mysqli,$qry);
if($result) {
if(mysqli_num_rows($result) > 0) {
echo "Email already in use";
}
#mysqli_free_result($result);
}
else {
die("Query failed");
}
}
$activation = md5(uniqid(rand(), true));
if ($stmt = "INSERT INTO users(firstname, lastname, email, password, verification, phone)"
." values('$fname', '$lname', '$email', '$password', "
. "'$activation','$phone')" or
die("Could not perform query ".mysqli_error($mysqli))) {
$result = mysqli_query($mysqli, $stmt)
or die("The system could not register you"
. "".mysqli_error($mysqli) . "<br>" . $stmt);
if ($result){
echo "sent";
}
//echo "<a href=\"gethotel.php?hid=".$row['hotel_id'].
//
/* close statement */
//$stmt->close();
}
}
?>
The issue us because you are hooking to the click event of the submit button and are not preventing the event from completing.
Also note that your selector to build the querystring is incorrect, as there should be a space before the : and not between the : and input, eg $("#register-form :input")
To fix the issues hook to the submit event of the form and use preventDefault(). Try this:
$("#register-form").submit(function(e) {
e.preventDefault();
if ($("fname").val().trim() == "" || $("lname").val().trim() == "") {
$("div#ack").html("Please enter both your first name and your surname");
} else {
$.post(this.action, $(this).find(':input').serializeArray(), function(data) {
$("div#ack").html(data);
});
}
});

Two form on a single page : How to identify which form validate using jquery ajax function

I have a html page which contains
a form with fields for sign up (registration / new member)
a form for sign in (login for already member)
The sign in form is :
<form class="dialog-form">
<div class="form-group">
<label>E-mail</label>
<input type="text" placeholder="email#domain.com" class="form-control">
</div>
<div class="form-group">
<label>PAssword</label>
<input type="password" placeholder="My PAssword" class="form-control">
</div>
<input type="submit" name="sign_in" value="Connexion" class="btn btn-primary">
</form>
The sign up form is :
<form class="dialog-form" action="bat/user_validation.php" method="post">
<div class="form-group">
<label>E-mail</label>
<input type="text" placeholder="email#domain.com" class="form-control">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" placeholder="My secret password" class="form-control">
</div>
<div class="form-group">
<label>Repeat Password</label>
<input type="password" placeholder="Type your password again" class="form-control">
</div>
<input type="submit" name="sign_up" value="Inscription" class="btn btn-primary">
</form>
One the other side, I have a php script file which contains function to check and insert a userid.
function getPassword($utilisateur) {
try {
$dbh = new PDO(DSN, USER, PASS);
$uid = $utilisateur;
$sql = "SELECT password FROM cc_users WHERE uid =:uid";
$sth = $dbh->prepare($sql);
$sth->execute(array(':uid'=>$uid));
$result = $sth->fetchAll();
return (count($result) == 1) ;
} catch (PDOException $e) {
print "Erreur ! : " . $e->getMessage() . "<br/>";
die();
}
}
function setPassword($uid, $pass) {
$dbh = new PDO(DSN, USER, PASS);
$sql = "UPDATE cc_users SET password =:pass where uid =:uid";
$sth = $dbh->prepare($sql);
$sth->execute(array(':pass'=>$pass ,':uid'=>$uid));
echo $count = $sth->rowCount();
return $dbh->exec($sql);
}
function newPassword($utilisateur, $pass) {
$crypt = crypt($pass);
return setPassword($utilisateur, $crypt);
}
function checkPassword($utilisateur, $pass) {
if (empty($pass)) return FALSE;
$interne = getPassword($utilisateur);
$crypt = crypt($pass, $interne);
return ($interne === $crypt);
}
print_r($_POST);
My questions are :
How I can check on which form the user is coming?
How can I do an $.ajax call for checking the form? If yes how?
Thanks
HTML:
Form 1:
<form id="form1">
<input type="submit" value="submit" />
</form>
Form 2:
<form id="form2">
<input type="submit" value="submit" />
</form>
jQuery:
$('form').on('submit', function () {
console.log($(this).attr('id')); // Logs the id of the submitted form
});
Give name for <form>
<form class="dialog-form" name="signin">
<form class="dialog-form" action="bat/user_validation.php" method="post" name="signup">
You can check $_POST global to see if it contains the name of your <input type="submit" />. It will contain either sign_up or sign_in, depending on what button did the user press.
For example:
if(isset($_POST['sign_up']){
$signingUp = true;
}
If you want to submit the form using jQuery ajax, you can use the following code snippet:
$.post('bat/user_validation.php', $('form.dialog-form').serialize());
Though the selector should be more concrete, probably including a form ID to distinguish between the two forms.

Categories

Resources