Javascript Validation if statement - php

I'm trying to use javascript validation for a simple login form. Right now I'm just focusing on the username input (Want it to display as red and have the error below it "That username is already taken" if the username is already taken). However, nothing shows up when the input is changed even though when I did inspect element network I saw that it was going to the registerjs.php file
In the head of the html form page i have
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
function valusername() {
var username = $('input#username').val();
if ($.trim(username) != '') {
$.post('../ajax/registerjs.php', {username: username}, function(data) {
if (data == 'That username is already taken') {
document.getElementById("username").style.border="3px solid red";
$('div#username_error').text(data);
}
});
}
}
</script>
The actual text input is
<input class="input" type="text" tabindex="1" placeholder="Username*"
style="height:20px;" name="username" id="username" onchange="valusername()">
<div id="username_error"></div>
The php file registerjs.php that is linked I'm sure works
<?php
include('../init.php');
if (isset($_POST['username']) === true && empty($_POST['username']) === false) {
$username = $_POST['username'];
if (user_exists($username) === true) {
echo("
That username is already taken
");
} else {
echo("Good");
}
}
?>
Does anyone know why I'm having this problem? It seems to be the if statement in the script.

Do this :
function valusername()
{
var username = $('input#username').val();
if ($.trim(username) != '')
{
$.post('../ajax/registerjs.php', {username: username}, function(data)
{
if ($.trim(data) == 'That username is already taken')
{
document.getElementById("username").style.border="3px solid red";
$('div#username_error').text(data);
}
});
}
}

Better Approach:
<input class="input" type="text" tabindex="1" placeholder="Username*"
style="height:20px;" name="username" id="username" >
<div id="username_error"></div>
JS
<script>
$(function(){
$(document).on('change paste','#username', function () {
var username = $(this).val();
if ($.trim(username) !== '') {
$.post('../ajax/registerjs.php', {username: username},
function(data){
if (data) {
$("#username").css({'border','3px solid red'});
$('div#username_error').text('Username already exist');
return false;
}
}
); // end of $.post
} // end of if
})
})
</script>
registerjs.php
<?php
include('../init.php');
// here i assume user_exists return true or false
if ( !empty($_POST['username']) && user_exists($username)) {
return TRUE;
}
else{
return FALSE;
}
?>

Related

PHP, Ajax login form issue

I am developing php login form using ajax control, actually I am new to this concept. I have index.php from there, I am sending username and password through ajax method. Ajax function will call ajaxAdminLogin.php, After doing user verification process it is not redirecting to dashboard.php. Here is my code please help me
index.php
<body>
<div class="loginbg">
<div class="container">
<div class="row content-area">
<div class="col-md-6 company-profile">
<div id="" class="adminLoginText">
<h1>Admin Login</h1>
</div>
<div id="" class="comapny-text">
<h3>Uni Web Tech</h3>
<p>Website Designing & Development</p>
</div>
</div>
<div class="col-md-6 login-form">
<div id="" class="login-form-area">
<form method="post">
<div class="form-group">
<label for="admin-username">User Name</label>
<input id="admin-username" class="form-control" type="text" name="adminUsername" required>
</div>
<div class="form-group">
<label for="admin-password">Password</label>
<input id="admin-password" class="form-control" type="password" name="adminPassword" required>
</div>
<button type="button" class="btn btn-primary" name="adminLogin" id="adminLogin">Login</button>
</form>
Forgot Password?
<p style="margin-top:30px;text-align:center;color:#ea6957;" id="login-error"></p>
</div>
</div>
</div>
</div>
</div>
</body>
<script type="text/javascript" src="js/adminloginJs.js"></script>
adminloginJs.js
<script>
$("document").ready(function () {
$("#adminLogin").click(function () {
var adminUsername = $("#admin-username").val().trim();
var adminPassword = $("#admin-password").val().trim();
if (adminUsername != "" && adminPassword != "")
{
$.ajax({
type: 'POST',
url: "ajax/ajaxAdminLogin.php?adminUsername=" + adminUsername + "&adminPassword=" + adminPassword,
cache: false,
success: function (message) {
$("#login-error").text("");
$("#login-error").text(message);
if ($("#login-error").text().trim() == "Done") {
window.location.href = "http://localhost/unidashboard/dashboard.php";
}
}
});
/*$.post("ajaxAdminLogin.php",{adminUsername: adminUsername, adminPassword: adminPassword})
.done(function(data){
if(data.trim() == "Done"){
window.location = "dashboard.php";
}
else{
$("#login-error").text(data);
}
});*/
} else
{
$("#login-error").text("");
$("#login-error").text("Please enter Username and Password");
}
});
});
</script>
ajaxAdminLogin.php
<?php
session_start();
/* Uni Web Tech Online Exam DB Connection */
include("includes/dbConnection.php");
/* Tracking User IP Address */
function get_ip_address() {
foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key) {
if (array_key_exists($key, $_SERVER) === true) {
foreach (explode(',', $_SERVER[$key]) as $ip) {
$ip = trim($ip); // just to be safe
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false) {
return $ip;
}
}
}
}
}
$AdminIPAddress = get_ip_address();
$username = $_POST['adminUsername'];
$password = $_POST['adminPassword'];
/* Fetching User Data */
$LoginSql = "select AdminId, Email, Password, Role, Status from adminusers where AdminId = '$username' or Email = '$username'";
$result = $uni_DB_Con->query($LoginSql);
if ($result->num_rows > 0) {
// fetching user details
while ($row = $result->fetch_assoc()) {
//verifying Enabled or Disabled
if ($row['Status'] == "Enable") {
// verifying username
if ($row['AdminId'] == $username || $row['Email'] == $username) {
if ($row['Password'] == $password) {
$AdminId = $row['AdminId'];
/* updating user login status 0 to 1 in users table */
$loginStatusSql = "UPDATE adminusers SET LoginStatus=1 WHERE AdminId = '$AdminId'";
$uni_DB_Con->query($loginStatusSql);
/* Creating session */
$_SESSION["AdminId"] = $AdminId;
$_SESSION["Role"] = $row['Role'];
/* Details for Activity */
$Login = Date("d - F - Y H:i:s");
$loginActivitySql = "INSERT INTO admin_activity(AdminId, AdminIPAddress, Login, Logout) VALUES ('$AdminId','$AdminIPAddress','$Login','0')";
$uni_DB_Con->query($loginActivitySql);
/* After storing login date and time navigating to dashboard page */
echo "Done"; /* redirect done from adminlogin.js */
} else {
echo "Invalid Password.";
}
} else {
echo "Invalid Username.";
}
} else {
echo "Sorry, You are disabled. Please contact admin.";
}
}
}
?>
please tell me, If I did any mistake.
Check The Commented part in the script below maybe its casue your passing a query stirng and your using a post in the server to pick up the data
<script>
$("document").ready(function () {
$("#adminLogin").click(function () {
var adminUsername = $("#admin-username").val().trim();
var adminPassword = $("#admin-password").val().trim();
if (adminUsername != "" && adminPassword != "")
{
$.ajax({
type: 'POST',
////From Here Replace and add these /////
url: "ajax/ajaxAdminLogin.php,
data:{'adminusername':adminUsername,'adminPassword':adminPassword}
dataType: 'HTML',
//////////////////////////////////////
cache: false,
success: function (message) {
console.log(message)
$("#login-error").text("");
$("#login-error").text(message);
if ($("#login-error").text().trim() == "Done") {
window.location.href = "http://localhost/unidashboard/dashboard.php";
}
}
});
/*$.post("ajaxAdminLogin.php",{adminUsername: adminUsername, adminPassword: adminPassword})
.done(function(data){
if(data.trim() == "Done"){
window.location = "dashboard.php";
}
else{
$("#login-error").text(data);
}
});*/
} else
{
$("#login-error").text("");
$("#login-error").text("Please enter Username and Password");
}
});
});
</script>

Receiving success response but the button still disabled using ajax

I am checking email id is available or not in the database using ajax which is working.I have one submit button and that is disabled on page load.I have to enable that button when the user enters the right email address which is available on the database. If email is available in the database the button will enable otherwise button will be disabled.There is some issue in if condition. I tried button still the same issue. Would you help me in this?
$("input[type='submit']").removeAttr("disabled");
$("input[type='submit']").prop('disabled', false);
If I used CSS for button then disable is not working.
Html
<input type="email" id="email" name="email" class="text_field" />
<span id="email-validation-error" class="error"></span>
<input id="id" type="submit" name="next" value="submit" >
Ajax
$(document).ready(function()
{
$("input[name='email']").on('keyup',function()
{
var email = $('#email').val();
$.ajax(
{
url:'process.php',
type:'POST',
data:'email='+email,
success:function(data)
{
if (data == 1) {
$('input[type="submit"]').attr('disabled' , false);
}
else{
$("#email-validation-error").html(data);
$('input[type="submit"]').attr('disabled', true);
}
},
});
});
});
//Disable the button on page load
$(document).ready(function() {
$('input[type="submit"]').attr('disabled', true);
});
Process.php
include('db/connection.php');
if(isset($_POST['email'])){
$email=$_POST['email'];
$query="SELECT Email FROM `request` WHERE Email='".$email."'";
$result = $conn->query($query);
$search_record=$result->num_rows;
if ($search_record == 0) {
echo "Email does not exist, please sign up to use our services";
}
}
Try this-
$(document).ready(function()
{
var elem = $("#id"); //assign target element with id
$("input[name='email']").on('keyup',function()
{
var email = $('#email').val();
$.ajax(
{
url:'process.php',
type:'POST',
data:'email='+email,
success:function(data)
{
if (data == "ok") {
$(elem).attr('disabled' , false); //here pass elem
}
else{
$("#email-validation-error").html('Email not available');
$(elem).attr('disabled', true); //here pass elem
}
},
});
});
});
Process.php
include('db/connection.php');
if(isset($_POST['email'])){
$email=$_POST['email'];
$query="SELECT Email FROM `request` WHERE Email='".$email."'";
$result = $conn->query($query);
$search_record=$result->num_rows;
if ($search_record == 0) {
echo "ok";
}
}
You should check and verify your response:
Process.php
if ($search_record == 0) {
echo "Email does not exist, please sign up to use our services";
}
else{
echo "success";
}
Ajax
if (data == "success") {
$("#submitYesNo").prop('disabled', false);
}
else{
$("#email-validation-error").html(data);
$("#submitYesNo").prop('disabled', true);
}
html
<input id="submitYesNo" type="submit" name="next" value="submit" >
Try This Code .
Hope it will work properly
success:function(data)
{
if (data == 1)
{
$('input[type="submit"]').removeAttr("disabled", "disabled");
}
else
{
$("#email-validation-error").html(data);
$('input[type="submit"]').attr("disabled", "disabled");
}
Finally, I found my answer with the help of Mr.Ahmed Ginani
HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form >
<input type="email" id="email" name="email" class="text_field" />
<span id="email-validation-error" class="error"></span>
<input id="id" type="submit" name="next" value="submit" disabled>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
var elem = $("#id"); //assign target element with id
$(elem).attr('disabled', true);
$("input[name='email']").bind('change',function() // Changes from key press to change and bind
{
var email = $('#email').val();
$.ajax(
{
url:'process.php',
type:'POST',
data:'email='+email,
success:function(data)
{
if (data == 'success') { // getting success name from process.php page
$("#id").attr('disabled' , false);
$("#email-validation-error").html(''); //Change here for hiding the error message
}
else{
$("#email-validation-error").html(data);
$('#id').attr('disabled', true);
}
},
});
});
});
</script>
</body>
</html>
Process.php
if(isset($_POST['email'])){
$email=$_POST['email'];
$_SESSION['username']=$email;
$query="SELECT Email FROM `request` WHERE Email='".$email."'";
$result = $conn->query($query);
$search_record=$result->num_rows;
if ($search_record > 0) {
echo "success";
}
else{
echo "Email does not exist, please sign up to use our services";
}
}

Javascript window.location.href redirection not working

Upon entering correct username/password, login success appears. I want to redirect to different page upon successful login, but window.location.href not working.
index.html
<form id="myFormlogin" action="login.php" method="POST">
Email:
<input type="text" name="usernamelogin" />
<br />Password:
<input type="password" name="passlogin" />
<br />
<button id="login">login</button>
</form>
<div id="ack"></div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="my_script.js"></script>
login.php
<?php
include_once('db.php');
$username = mysql_real_escape_string($_POST["usernamelogin"]);
$password = mysql_real_escape_string(md5($_POST["passlogin"]));
$sql = "SELECT * FROM registered_users WHERE username='$username' and password='$password'";
$result = mysql_query($sql);
if ($result) {
echo "login success";
} else {
echo "Wrong Username or Password";
}
?>
script.js
("#login").click( function() {
if( $("#usernamelogin").val() == "" || $("#passlogin").val() == "" )
$("#ack").html("Username/Password are mandatory fields -- Please Enter.");
else
window.location.href = "http://jsfiddle.net/";
});
Use id instead of name
chnage your code as
Email: <input type="text" id="usernamelogin"/><br />
Password: <input type="password" id="passlogin"/><br />
instead of
Email: <input type="text" name="usernamelogin"/><br />
Password: <input type="password" name="passlogin"/><br />
And use return false to prevent default action
$("#login").click(function () {
if ($("#usernamelogin").val() == "" || $("#passlogin").val() == "")
$("#ack").html("Username/Password are mandatory fields -- Please Enter.");
else
window.location.href = "http://www.google.com";
return false;
});
Demo: http://jsfiddle.net/satpalsingh/SzhbM/
I suspect the form may be submitting. Try preventing the default action of the form.
$("#login").click( function(e) {
e.preventDefault();
if( $("#usernamelogin").val() == "" || $("#passlogin").val() == "" )
$("#ack").html("Username/Password are mandatory fields -- Please Enter.");
else
window.location.href = "http://google.com";
});
First of all use ID selector instead of name. so add ID in both input :
Email: <input type="text" name="usernamelogin" id="usernamelogin"/><br />
Password: <input type="password" name="passlogin" id="passlogin"/><br />
Then change function to :
$(document).ready(function(){
$("#login").click( function() {
if( $("#usernamelogin").val() == "" || $("#passlogin").val() == "" )
$("#ack").html("Username/Password are mandatory fields -- Please Enter.");
return false;
else
window.location.href = "http://google.com";
return false;
});
});
And set return false that will prevent default action.
Wrap code inside $(document).ready(); and also user preventDefault so it will execute only defined code.
Example
$("#login").click( function(e)
{
e.preventDefault();
Also you are using if( $("#usernamelogin").val() == "" || $("#passlogin").val() == "" ) this code but you forget to assign ID to the input fields.
And that is why jQuery was unable to find that two fields and stop executing script further.
You can check it in firebug.
Comment Code Response
Made below changes in index.html page.
<form id="myFormlogin" action="login.php" method="POST">
Email: <input type="text" id="usernamelogin" name="usernamelogin"/><br />
Password: <input type="password" id="passlogin" name="passlogin"/><br />
<button id="login">login</button>
</form>
what i did is added name attribute for the input fields.
replace your mys_script.js with below code
$(function()
{
$("#submit").click( function()
{
if( $("#username").val() == "" || $("#pass").val() == "" )
{
$("#ack").html("Username/Password are mandatory fields -- Please Enter.");
}
else
{
$.ajax({
url : $('#myForm').attr('action'),
data : $('#myForm').serialize(),
success : function(info)
{
$("#ack").empty();
$("#ack").html(info);
clear();
}
});
}
});
function clear()
{
$("form :input").each( function() {
$(this).val("");
});
}
$("#login").click( function()
{
if( $("#usernamelogin").val() == "" || $("#passlogin").val() == "" )
{
$("#ack").html("Username/Password are mandatory fields -- Please Enter.");
}
else
{
$.ajax({
url : $('#myFormlogin').attr('action'),
data : $('#myFormlogin').serialize(),
success : function(info)
{
$("#ack").empty();
$("#ack").html(info);
clear();
}
});
}
});
});
and finally make changes in your login.php file as below,
<?php
include_once('db.php');
$username = mysql_real_escape_string( $_POST["usernamelogin"] );
$password = mysql_real_escape_string( md5($_POST["passlogin"]) );
$sql="SELECT * FROM registered_users WHERE username='$username' and password='$password'";
$result=mysql_query($sql)or die(mysql_error());
$count = mysql_num_rows($result);
if($count==1)
{
echo "found user";
}
else
{
echo "Wrong Username or Password";
}
?>

Php response displays in browser instead of firing the ajax callback

I've spent some time looking on SO for an answer to this and have found some related issues, but nothing quite like mine...as usual....
I've got a fairly simple php/jquery ajax registration page that is working right up until the ajax callback. What I mean is the form data is passing to php and inserting into the db but when the php response is supposed to come back all that happens is the response displays in the browser. I've followed the logs, checked fiddler, re-written the code with/without json, and anothing seems to change. The odd thing is I have another form on a different page that is set up exactly the same way and everything works there perfectly. The only difference I can find between the two pages is the Request Headers of the php file. The one that works accepts json and the one the other one doesn't, but I have no idea if that means anything . . . I'm kind of grabbing for anything at this point.
So, without further delay, here is my code. Any thoughts/input are greatly appreciated. Thank you!
<!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="mobile.css" media="screen and (max-device-width: 480px)" />
<!--[if IE]>
<link rel="stylesheet" type="text/css" media="screen and (min-width: 481px)" href="IEjoin.css" />
<![endif]-->
<script src="jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="register.js" type="text/javascript"></script>
<script src="jquery.placeholder.js" type="text/javascript"></script>
</head>
<body>
<div id="wrapper">
<div id="logo">
</div>
<div id="headline">
<h1>Create your account</h1>
</div>
<div id="container">
<form id="register" action="form.php" method="post">
<ul>
<li id="first_name">
<input name="fname" type="text" value="" id="fname" placeholder="First Name" maxlength="30">
<div class="error"></div>
</li>
<li id="last_name">
<input name="lname" type="text" value="" id="lname" placeholder="Last Name" maxlength="30">
<div class="error"></div>
</li>
<li id="email_address">
<input name="email" type="text" value="" id="email" placeholder="Email Address" maxlength="60">
<div class="error"></div>
</li>
<li id="uname">
<input name="username" type="text" value="" id="username" placeholder="Username" maxlength="15">
<div class="error"></div>
</li>
<li id="pword">
<input name="password" type="password" value="" id="password" placeholder="Password">
<div class="error"></div>
</li>
<li id="gender_select">
<select id="gender" name="gender">
<option value="" selected="selected">Select your gender</option>
<option value="male">Male</option>
<option value="female">Female</option>
<option value="unspecified">Unspecified</option>
</select>
</li>
<li id="submit_button">
<button id="register_button" class="register_button_disabled">Create Account</button>
</li>
</ul>
</form>
<script> $('input[placeholder]').placeholder();</script>
</div>
</div>
</body>
$(document).ready(function() {
function validateEmail(email) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
return emailReg.test(email);
}
function submitButton() {
if (($("#first_name").hasClass("good")) && ($("#email_address").hasClass("good")) && ($("#uname").hasClass("good")) && ($("#pword").hasClass("good")) ){
$("#register_button").removeAttr("disabled");
$("#register_button").removeClass("register_button_disabled").addClass("register_button");
} else {
$("#register_button").attr("disabled", "disabled");
$("#register_button").removeClass("register_button").addClass("register_button_disabled");
}
}
$("body").mousedown(submitButton);
$("body").keyup(submitButton);
$("body").hover(submitButton);
$("body").mouseover(submitButton);
$("#fname").keydown(function(){
$("#first_name").removeClass("required");
$("#first_name div").html("");
});
$("#fname").bind ("keyup mousedown",function(){
if(this.value===""){
$("#first_name").removeClass("good").addClass("wait");
} else {
$("#first_name").removeClass("wait").addClass("good");
}
});
$("#fname").blur(function(){
if(this.value===""){
$("#first_name").removeClass("good").addClass("required");
$("#first_name div").html("Please enter your first name");
} else {
$("#first_name").removeClass("wait").addClass("good");
}
});
$("#email").keydown(function(){
$("#email_address").removeClass("required");
$("#email_address div").html("");
});
$("#email").bind ("keyup mousedown",function(){
var email = this.value;
var emailLength = email.length;
if (emailLength<=4){
$("#email_address").removeClass("good").addClass("wait");
} else {
$("#email_address").removeClass("wait").addClass("good");
}
});
$("#email").blur(function(){
var email = this.value;
var emailLength = email.length;
if ((emailLength<=4) || (!validateEmail(this.value))) {
$("#email_address").removeClass("good").addClass("required");
$("#email_address div").html("Please use a valid email address");
} else if (emailLength>=3){
$.ajax({
type: "POST",
cache: false,
url: "Check.php",
data: "email="+email,
dataType: "json",
success: function(data) {
if (data.status === "success") {
$("#email_address").removeClass("good").addClass("required");
$("#email_address div").html("Sorry, that email is already used");}
else {
$("#email_address").removeClass("wait").addClass("good");
}
}
});
} else {
$("#email_address").removeClass("wait").addClass("good");
}
});
$("#username").keydown(function(){
var un = this.value;
var unLength = un.length;
if(unLength<3){
$("#uname").removeClass("good").addClass("wait");
} else {
$("#uname").removeClass("wait").addClass("good");
}
});
$("#username").bind ("keyup mousedown",function(){
$("#uname").removeClass("required");
$("#uname div").html("");
});
$("#username").blur(function(){
var un = this.value;
var unLength = un.length;
if(unLength<3){
$("#uname").removeClass("good").addClass("required");
$("#uname div").html("Please use at least 3 characters");
} else if (unLength>=3){
$.ajax({
type: "POST",
cache: false,
url: "check.php",
data: "username="+un,
dataType: "json",
success: function(data) {
if (data.status === "success") {
$("#uname").removeClass("good").addClass("required");
$("#uname div").html("Sorry, that username is taken");
} else {
$("#uname").removeClass("wait").addClass("good");
}
}
});
} else {
$("#uname").removeClass("wait").addClass("good");
}
});
$("#password").keydown(function(){
var pw = this.value;
var pwLength = pw.length;
if(pwLength<=5){
$("#pword").removeClass("good").addClass("wait");
} else {
$("#pword").removeClass("wait").addClass("good");
}
});
$("#password").bind ("keyup mousedown",function(){
$("#pword").removeClass("required");
$("#pword div").html("");
});
$("#password").blur(function(){
var pw = this.value;
var pwLength = pw.length;
if(pw===""){
$("#pword").removeClass("good").addClass("required");
$("#pword div").html("Please enter a password");
}
if(pwLength<=5){
$("#pword").removeClass("good").addClass("required");
$("#pword div").html("Please use at least 6 characters");
} else {
$("#pword").removeClass("wait").addClass("good");
}
});
$("#button").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
cache: false,
url: "form.php",
data: $('#register').serialize(),
success: function(data) {
if (data === "fname") {
$("#first_name").removeClass("good").addClass("required");
$("#first_name div").html("Please enter your first name");
} else if (data === "email") {
$("#email_address").removeClass("good").addClass("required");
$("#email_address div").html("Please use a valid email address");
} else if (data === "email2") {
$("#email_address").removeClass("good").addClass("required");
$("#email_address div").html("Sorry, that email is already used");
} else if (data === "username") {
$("#uname").removeClass("good").addClass("required");
$("#uname div").html("Please use at least 3 characters");
} else if (data === "username2") {
$("#uname").removeClass("good").addClass("required");
$("#uname div").html("Sorry, that username is taken");
} else {
window.location.href = "http://site.com";
},
error: function(httpRequest, textStatus, errorThrown) {
alert("status=" + textStatus + ",error=" + errorThrown);
}
});
return false;
});
});
<?php
$host=""; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name=""; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Get values from form
$fname = mysql_real_escape_string($_POST['fname']);
$lname = mysql_real_escape_string($_POST['lname']);
$email = mysql_real_escape_string($_POST['email']);
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$gender = mysql_real_escape_string($_POST['gender']);
//validate inputs
$emailpull = "SELECT email FROM $tbl_name WHERE email='$email'";
$emailresult=mysql_query($emailpull);
$emailnum=mysql_num_rows($emailresult);
$emailReg = "/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/";
$unpull = "SELECT username FROM $tbl_name WHERE username='$username'";
$unresult=mysql_query($unpull);
$unnum=mysql_num_rows($unresult);
if ($fname == "") {
$response = "fname";
} elseif ($email == "") {
$response = 'email';
} elseif (!preg_match($emailReg, $email)) {
$response = 'email';
} elseif ($emailnum > 0) {
$response = 'email2';
} elseif (strlen($username)<3) {
$response = 'username';
} elseif ($unnum > 0) {
$response = 'username2';
} elseif (strlen($password)<6) {
$response = 'password';
} else {
// Insert data into mysql
$sql="INSERT INTO $tbl_name(fname,lname,email,username,password,gender)VALUES ('$fname','$lname','$email','$username','$password','$gender')";
}
$result=mysql_query($sql);
if($result)
$response = "success";
// send message back
echo $response;
?>
<?php
// close connection
mysql_close();
?>
The click handler for #button has this line which may be the culprit:
window.location.href = "http://crushonit.com";
This will redirect to that page when the form has no validation errors.

PHP - verify if user exist in DB and display the result without reloading the page

I want to check if a user exists in DB, and if exist display some error without reload the page (modify a div). Any idea what is wrong in this code? Or any other idea how to do it? Thank you
HTML:
<div style="width:510px; height:500px;">
<div class="message">
<div id="alert"></div>
</div>
<form id="signup_form" method="post" action="register.php">
<label class="label">username</label>
<p><input class="signup_form" type="text" name="username"></p>
<label class="label">parola</label>
<p><input class="signup_form" type="text" name="password"></p>
<label class="label">name</label>
<p><input class="signup_form" type="text" name="name"></p>
<label class="label">telefon</label>
<p><input class="signup_form" type="text" name="phone"></p>
<label class="label">email</label>
<p><input class="signup_form" type="text" name="email"></p>
<p><input class="signup_button" type="submit" value="inregistrare">
</form>
<div class="clear"></div>
</div>
register.php
<?php
include "base.php";
$usertaken = '<li class="error">username used</li><br />';
$alert = '';
$pass = 0;
if(!empty($_POST['username']) && !empty($_POST['password']))
{
$username = mysql_real_escape_string($_POST['username']);
$password = md5(mysql_real_escape_string($_POST['password']));
$name = mysql_real_escape_string($_POST['username']);
$phone = mysql_real_escape_string($_POST['phone']);
$email = mysql_real_escape_string($_POST['email']);
$checkusername = mysql_query("SELECT * FROM details WHERE user = '".$username."'");
if(mysql_num_rows($checkusername) == 1)
{
$pass = 1;
$alert .="<li>" . $usertaken . "</li>";
}
else
{
$registerquery = mysql_query("INSERT INTO details (user, pass, name, phone, email) VALUES('".$username."', '".$password."','".$name."','".$phone."', '".$email."')");
if($registerquery)
{
echo "<h1>Success</h1>";
echo "<p>Your account was successfully created. Please click here to login.</p>";
}
else
{
echo "<h1>Error</h1>";
echo "<p>Sorry, your registration failed. Please go back and try again.</p>";
}
}
if($pass == 1) {
echo '<script>$(".message").hide("").show(""); </script>';
echo "<ul>";
echo $alert;
echo "</ul>";
}
}
?>
SOLUTION (add this in head and hide .message div)
<script type="text/javascript" src="jquery-latest.pack.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var options = {
target: '#alert',
beforeSubmit: showRequest,
success: showResponse
};
$('#signup_form').ajaxForm(options);
});
function showRequest(formData, jqForm, options) {
var queryString = $.param(formData);
return true;
}
function showResponse(responseText, statusText) {
}
$.fn.clearForm = function() {
return this.each(function() {
var type = this.type, tag = this.tagName.toLowerCase();
if (tag == 'form')
return $(':input',this).clearForm();
if (type == 'text' || type == 'password' || tag == 'textarea')
this.value = '';
else if (type == 'checkbox' || type == 'radio')
this.checked = false;
else if (tag == 'select')
this.selectedIndex = -1;
});
};
</script>
You need to use AJAX to do a dynamic page update.
Take a look here: http://api.jquery.com/jQuery.ajax/ for how to do it with jQuery.
Your current code uses a form submit, which always reloads the page.
You need to use ajax. Write something like this as a JavaScript:
var xmlHttp;
function checkUser(user) {
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null) {
alert ("Browser does not support HTTP Request.");
return;
}
var url = "check.php"; //This is where your dynamic PHP file goes
url = url + "?u=" + user;
url = url + "&sid=" + Math.random();
xmlHttp.onreadystatechange = getData;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function getData () {
if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
if (xmlHttp.responseText == 1) {
alert('Username free'); //action if username free
} else {
alert('This username is taken'); //action if its not
}
}
}
function GetXmlHttpObject() {
var xmlHttp=null;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
} catch (e) {
//Internet Explorer
try {
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
And in your check.php file, just check against your database if the username is taken or not, if not and simply echo('1') if its free, else echo('0') o whatever you want. that single number will be handled as the xmlHttp.responseText. you can also do something fancy instead of the alerts, like an image. also you need to run the check() fumction either when the user is typing, or when the form is submitted, with the username form field as a parameter. Hope this helps.
EDIT: Oh, also I forgot that in the check.php file, the $_GET['u'] variable contains the the entered username. Check that against the database.
If that's all in a single page, you'll have to structure it like this:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... do form retrieval/database stuff here ...
if (error) {
$message = 'Something dun gone boom';
}
}
if ($message != '') {
echo $message;
}
?>
form stuff goes here

Categories