Validation display name using jQuery remote method - php

I've tried to added remote method to check display name if is has already exists.
Email validation can check and display messages if email has already exists but Display name validation it does not work. What's wrong with my code?
My code
register.php
<?php require_once 'config.php'; ?>
<?php
if(!empty($_POST)){
try {
$user_obj = new Cl_User();
$data = $user_obj->registration( $_POST );
if($data)$success = USER_REGISTRATION_SUCCESS;
} catch (Exception $e) {
$error = $e->getMessage();
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Smart Registration Form</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/font-awesome.min.css" rel="stylesheet">
<link href="css/login.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="js/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="login-form">
<?php require_once 'templates/message.php';?>
<h1 class="text-center">Smart Tutorials</h1>
<div class="form-header">
<i class="fa fa-user"></i>
</div>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" class="form-register" role="form" id="register-form">
<div>
<input name="name" id="name" type="text" class="form-control" placeholder="Dispaly Name">
<span class="help-block"></span>
</div>
<div>
<input name="email" id="email" type="email" class="form-control" placeholder="Email address" >
<span class="help-block"></span>
</div>
<div>
<input name="password" id="password" type="password" class="form-control" placeholder="Password">
<span class="help-block"></span>
</div>
<div>
<input name="confirm_password" id="confirm_password" type="password" class="form-control" placeholder="Confirm Password">
<span class="help-block"></span>
</div>
<button class="btn btn-block bt-login" type="submit" id="submit_btn" data-loading-text="Signing Up....">Sign Up</button>
</form>
<div class="form-footer">
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6">
<i class="fa fa-lock"></i>
Forgot password?
</div>
<div class="col-xs-6 col-sm-6 col-md-6">
<i class="fa fa-check"></i>
Sign In
</div>
</div>
</div>
</div>
</div>
<!-- /container -->
<script src="js/jquery.validate.min.js"></script>
<script src="js/register.js"></script>
</body>
</html>
register.js
$(document).ready(function(){
$("#register-form").validate({
submitHandler : function(form) {
$('#submit_btn').attr('disabled','disabled');
$('#submit_btn').button('loading');
form.submit();
},
rules : {
name : {
required : true,
name: true,
remote: {
url: "check-name.php",
type: "post",
data: {
name: function() {
return $( "#name" ).val();
}
}
}
},
email : {
required : true,
email: true,
remote: {
url: "check-email.php",
type: "post",
data: {
email: function() {
return $( "#email" ).val();
}
}
}
},
password : {
required : true
},
confirm_password : {
required : true,
equalTo: "#password"
}
},
messages : {
name : {
required : "Please enter name",
remote : "Diaplay name already exists"
},
email : {
required : "Please enter email",
remote : "Email already exists"
},
password : {
required : "Please enter password"
},
confirm_password : {
required : "Please enter confirm password",
equalTo: "Password and confirm password doesn't match"
}
},
errorPlacement : function(error, element) {
$(element).closest('div').find('.help-block').html(error.html());
},
highlight : function(element) {
$(element).closest('div').removeClass('has-success').addClass('has-error');
},
unhighlight: function(element, errorClass, validClass) {
$(element).closest('div').removeClass('has-error').addClass('has-success');
$(element).closest('div').find('.help-block').html('');
}
});
});
check-name.php
<?php
require_once 'config.php';
$db = new Cl_DBclass();
if( isset( $_POST['name'] ) && !empty($_POST['name'])){
$name = $_POST['name'];
$query = " SELECT count(name) cnt FROM users where name = '$name' ";
$result = mysqli_query($db->con, $query);
$data = mysqli_fetch_assoc($result);
if($data['cnt'] > 0){
echo 'false';
}else{
echo 'true';
}
exit;
}
?>
EDIT
check-email.php
<?php
require_once 'config.php';
$db = new Cl_DBclass();
if( isset( $_POST['password'] ) && !empty($_POST['password'])){
$password =md5( trim( $_POST['password'] ) );
$email = $_POST['email'];
if( !empty( $email) && !empty($password) ){
$query = " SELECT count(email) cnt FROM users where password = '$password' and email = '$email' ";
$result = mysqli_query($db->con, $query);
$data = mysqli_fetch_assoc($result);
if($data['cnt'] == 1){
echo 'true';
}else{
echo 'false';
}
}else{
echo 'false';
}
exit;
}
if( isset( $_POST['email'] ) && !empty($_POST['email'])){
$email = $_POST['email'];
$query = " SELECT count(email) cnt FROM users where email = '$email' ";
$result = mysqli_query($db->con, $query);
$data = mysqli_fetch_assoc($result);
if($data['cnt'] > 0){
echo 'false';
}else{
echo 'true';
}
exit;
}
?>

Related

Ajax Post to slim framework not responding

When the login button is pressed the form data is posted to the slim route url using ajax post method which is supposed to pass the data so that it can be retrieved by the framework,the data is passes to the check login function which checks that credentials entered and if it matches whats stored in the db returns true, and this response redirects to the homepage (projects.php). When i click the button nothing happens, the web application responds to debug output right up to the ajax post statement but from then on all other test output doesnt show up.
Slim index.php
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require 'vendor/autoload.php';
include 'lib.php';
$config = [
'settings' => [
'displayErrorDetails' => true,
]
];
// Create app
$app = new \Slim\App($config);
// Get container
$container = $app->getContainer();
// Register component on container
$container['view'] = function ($container) {
return new \Slim\Views\PhpRenderer('templates/');
};
$app->get('/', function (Request $request, Response $response) {
return $this->view->render($response, "/login.php");
});
$app->get('/guest', function (Request $request, Response $response) {
return $this->view->render($response, "/projects.php");
});
$app->get('/projects', function (Request $request, Response $response) {
return $this->view->render($response, "/projects.php");
});
$app->post("/login", function(Request $request, Response $response)use($app){
$post = $request->getParsedBody();
$email = $post['email'];
$password = $post['password'];
$res = checkLogin($email, $password);
if ($res===true){
$response = $response->withStatus(201);
$response = $response->withJson(array("status"=> true));
} else{
$response = $response->withJson(400);
}
return $response;
});
// Run app
$app->run();
lib.php :
<?php
if(!session_id()) session_start();//If session is not started start session
function getDBConnection(){
try{
$db = new mysqli("localhost","web_project","admin","web_project");
if ($db == null && $db->connect_errno > 0)return null;
return $db;
}catch(Exception $e){ }
return null;
}
function checkLogin($email, $password){
$password = sha1($password);
$sql = "SELECT * FROM `user` where `email`='$email'";
echo($email);
$db = getDBConnection();
print_r($db);
if($db != NULL){
$res = $db->query($sql);
if ($res && $row = $res->fetch_assoc()){
if($row['password'] == $password){
$_SESSION["user"] = $row['fname'];
$_SESSION["id"] = $row['uid'];
return true;
}
}
$db->close();
}
return false;
}
main.js:
"use strict";
$(document).ready(function() {
$('#loginform').bootstrapValidator({
container: '#messages',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok has-success',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
email: {
validators: {
notEmpty: {
message: 'Email is required and cannot be empty'
},
emailAddress: {
message: 'The email address is not valid'
}
}
},
password: {
validators: {
notEmpty: {
message: 'Password is required and cannot be empty'
}
}
}
}
});
$( "#btn-guest" ).click(function() {
window.location.href = 'index.php/guest';
});
$( "#btn-login" ).click(function() {
login();
});
});
function login(){
//var email = document.forms["logForm"]["email"].value;
// var password = document.forms["logForm"]["password"].value;
var email = $("#email").val();
var password = $("#password").val();
var data= {
"email" : email,
"password": password
};
console.log(data);
$.post("index.php/login", data, function(response){
console.log("Response: "+response);
var obj = JSON.parse(response);
console.log(obj.status);
if(obj.status == true){
window.location.href = "index.php/projects";
}else{
window.location.href = "/";
}
return false;
});
}
html page with form:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Login</title>
<!-- Bootstrap core CSS -->
<link href="bower_components/bootstrap/dist/css/bootstrap.css" rel="stylesheet">
<link href="css/ie10-viewport-bug-workaround.css" rel="stylesheet">
<link href="css/main.css" rel="stylesheet">
<script src="bower_components/sweetalert/dist/sweetalert.min.js"></script>
<link rel="stylesheet" type="text/css" href="bower_components/sweetalert/dist/sweetalert.css">
</head>
<body id="login_page">
<div id="header">
</div>
<?php if(isset($_SESSION["user"])){unset($_SESSION['user']);} ?>
<div class="container">
<div id="loginbox" style="margin-top:100px;" class="mainbox col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2">
<div class="panel panel-default" id="panel-default">
<div class="panel-heading" id="panel-heading">
<div class="panel-title">Sign In</div>
<div style="float:right; font-size: 80%; position: relative; top:-10px">Forgot password?</div>
</div>
<div style="padding-top:30px" class="panel-body" >
<div style="display:none" id="login-alert" class="alert alert-danger col-sm-12"></div>
<form id="loginform" enctype="multipart/form-data" name="logForm" class="form-horizontal" role="form" method="POST">
<div style="margin-bottom: 25px" class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input id="email" type="text" class="form-control" name="email" value="" placeholder="Email" >
</div>
<div style="margin-bottom: 25px" class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
<input id="password" type="password" class="form-control" name="password" placeholder="Password">
</div>
<!-- #messages is where the messages are placed inside -->
<div class="form-group">
<div class="col-md-9 col-md-offset-3">
<div id="messages"></div>
</div>
</div>
<div style="margin-top:10px" class="form-group">
<!-- Button -->
<div class="col-sm-12 controls">
<button type="button" id="btn-login" class="btn btn-info" value="Login">Login</button>
</div>
</div>
<div style="margin-top:10px" class="form-group">
<!-- Button -->
<div class="col-sm-12 controls">
<button type="button" id="btn-guest" class="btn btn-info" value="SignUp">Sign in as Guest</button>
</div>
</div>
<footer class="navbar navbar-fixed-bottom" id="footer">
</footer>
<script src="js/ie10-viewport-bug-workaround.js"></script>
<script src="bower_components/jquery/dist/jquery.js"></script>
<script src="bower_components/bootstrap/dist/js/bootstrap.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.3/js/bootstrapValidator.js"></script>
<script src="js/main.js"></script>
</body>
</html>

Retrieving username and password from Mongodb using php with angular js

I have created a simple login page using mongodb , angular js and php. when the user login from the database by retrieving username and password from the database, it goes to the admin page. But the login from database is not responding as unable to fetch data from db
index.php:
This is the homepage of the website.
<?php
include('login.php'); // Includes Login Script
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>LoginIN</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
<link href="styles/bootstrap.min.css" rel="stylesheet">
<link href="styles/signin.css" rel="stylesheet">
</head>
<body>
<?php
if(isset($error) and count($error) > 0){
?>
<div class="errorContainer"> <ul>
<?php foreach($error as $err) echo '<li>'.$err.'</li>'; ?>
</ul></div>
<?php
}
if(!empty($success)){
echo '<p class="text-success">'.$success.'</p>';
}
?>
<div id="wrapper">
<header id="top">
<center><h1>Leave Reporting System</h1></center>
<div class="container">
<div ng-app ='angularPost' ng-controller='loginCtrl'>
<form class="form-signin" role="form" action ="" method="post">
<h2 class="form-signin-heading">Please sign in</h2>
<input type="email" name="username" class="form-control" ng-model="username" placeholder="Email address" required autofocus>
<input type="password" name="password" class="form-control" ng-model="password" placeholder="Password" required>
<br>
<div class="checkbox">
<label>
<input type="checkbox" value="remember" name ="remember">Remember me
<br>
</label>
</div>
<input name="submit"button class="btn btn-lg btn-primary btn-block" ng-click=login() type="submit" value=" Sign in">
<span>{{responseMessage}}</span>
<br>
Forgot your password?
</form>
</div>
</body>
</html>
login.php
<?php
$succss = "";
if(isset($_POST['submitForm'] )){
$usr_email = $_POST['username'];
$usr_password = $_POST['password'];
$error = array();
if(empty($usr_email) or !filter_var($usr_email,FILTER_SANITIZE_EMAIL)){
$error[] = "Empty or invalid email address";
}
if(empty($usr_password)){
$error[] = "Enter your password";
}
if(count($error) == 0){
$con = new MongoClient();
if($con){
// Select Database
$db = $con->lrs;
// Select Collection
$Login = $db->Login;
$qry = array("username" => $usr_email,"password" => md5($usr_password));
$result = $Login->findOne($qry);
if($result){
$success = "You are successully loggedIn";
// Rest of code up to you....
}
} else {
die("Mongo DB not installed");
}
}
}
?>
app.js
var app = angular.module('angularPost',[]);
app.controller('loginCtrl', function($scope, $http)
{
$scope.login = function() {
var request = $http({
method : "post",
url : "login.php",
data : {
email : $scope.username,
password: $scope.password
},
});
request.success(function(data)
{
if(data == "1"){
$scope.responseMessage = "Successfully Logged in";
}
else{
$scope.responseMessage= "Username or Password is invalid"
}
});
}
});

Variables not passing between IF statements PHP

Okay so I'm writing a piece of code which checks a number of conditions which are set in IF statements in order to display a button to signup for a website. However, the variables I am declaring as true/false in my IF statements don't seem to be transferring over to the statement where it determined whether they are all true. Ive looked online and can't seem to find any problem like this anywhere, so i don't know if its me being stupid or there is a genuine problem. Here's my code:
<?php
include_once('db_conx.php');
//CHECKING USERNAME IS NOT TAKEN
if(!empty($_POST["username"])) {
$usernameAuth = false;
$username = $_POST['username'];
$sql = "SELECT * FROM users WHERE username='$username'";
$queryUname = mysqli_query($conn, $sql);
$username_check = mysqli_num_rows($queryUname);
if($username_check>0){
echo "Username Not Available.";
} else {
echo "Username Available.";
$usernameAuth = true;
}
}
//CHECKING EMAIL HAS NOT BEEN USED BEFORE
if(!empty($_POST["email"])) {
$emailAuth = false;
$email = $_POST['email'];
$sql = "SELECT * FROM users WHERE email='$email'";
$queryEmail = mysqli_query($conn, $sql);
$email_check = mysqli_num_rows($queryEmail);
if($email_check>0){
echo "Email already registered.";
} else {
$emailAuth = true;
}
}
//CHECKING THAT THE PASSWORDS MATCH AND ARE VALID
if(!empty($_POST["password1"]) && !empty($_POST["password2"])) {
$passAuth = false;
$password1 = $_POST['password1'];
$password2 = $_POST['password2'];
if($password1 != $password2) {
echo "Your passwords do not match.";
} elseif(!preg_match("#[0-9]+#",$password1)) {
echo "Your Password Must Contain At Least 1 Number!";
} elseif(!preg_match("#[A-Z]+#",$password1)) {
echo "Your Password Must Contain At Least 1 Capital Letter!";
} elseif(!preg_match("#[a-z]+#",$password1)) {
echo "Your Password Must Contain At Least 1 Lowercase Letter!";
} else {
$passAuth = true;
}
}
//CHECKING TO SEE IF ALL THE VALIDATION CONDITIONS ARE MET
if(!empty($_POST["checkinput"])){
if(($usernameAuth) && ($emailAuth) && ($passAuth)){
echo '<button id="button" class="btn waves-effect waves-light" type="submit" onclick="signup()" name="action">Register<i class="material-icons right">send</i></button>';
} else {
echo 'shite';
}
}
?>
If you need to know more or want any more pieces of the project, just say and I'm happy to provide them.
UPDATE
Added the AJAX JQUERY and index.php code:
<!DOCTYPE html>
<!--stylesheet -->
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<!-- MaterializeCSS -->
<link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link type="text/css" rel="stylesheet" href="css/materialize.min.css" media="screen,projection"/>
<!-- fullPage.js -->
<link rel="stylesheet" type="text/css" href="fullPage.js-master/jquery.fullPage.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="vendors/jquery.easings.min.js"></script>
<script type="text/javascript" src="fullPage.js-master/vendors/jquery.slimscroll.min.js"></script>
<script type="text/javascript" src="fullPage.js-master/jquery.fullPage.js"></script>
<!--TILE SCROLLING-->
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('#fullpage').fullpage({
verticalCentered: true,
sectionsColor: ['#1bbc9b', '#2c3e50', '#34495e'],
anchors: ['homepage', 'Login', 'Register'],
afterRender: function(){
//playing the video
$('video').get(0).play();
}
});
});
</script>
<!-- VALIDATING THE NEEDED FIELDS -->
<script type="text/javascript">
//CHECKING USERNAME
function UserAvailability() {
jQuery.ajax({
url: "scripts/validation.php",
data:'username='+$("#username").val(),
type: "POST",
success:function(data){
$("#user-availability-status").html(data);
},
error:function (){}
});
}
//CHECKING EMAIL
function EmailAvailability() {
jQuery.ajax({
url: "scripts/validation.php",
data:'email='+$("#email").val(),
type: "POST",
success:function(data){
$("#email-availability-status").html(data);
},
});
}
//CHECKING PASSWORDS MATCH
function passwordCheck() {
jQuery.ajax({
url: "scripts/validation.php",
data:'password1='+$("#password1").val()+'&password2='+$("#password2").val(),
type: "POST",
success:function(data){
$("#password-status").html(data);
},
});
}
//SIGNUP
function checkInput() {
jQuery.ajax({
url: "scripts/validation.php",
data:'checkinput=success',
type: "POST",
success:function(data){
$("#register-button").html(data);
},
});
}
//CHECKING LOGIN DATA IS VALID
function register() {
jQuery.ajax({
url: "scripts/validation.php",
data:'forename='+$("#firstName").val()+'&surname='+$("#lastName").val(),
type: "POST",
});
}
</script>
</head>
<body>
<div id="fullpage">
<div class="section " id="section0">
<video autoplay loop muted id="myVideo">
<source src="video/homeVideo.mp4" type="video/mp4">
</video>
<div class="layer">
<ul id="menu">
<li data-menuanchor="Login">Login</li>
<li data-menuanchor="Register">Register</li>
</ul>
</div>
<div class="layer">
<h1>Title</h1>
</div>
</div>
<div class="section" id="section1">
<div class="loginCard">
<form action ="scripts/login.php" method="post">
<input type="text" id="usernameLogin" name="username" placeholder="Username">
<input type="password" id="passwordLogin "name="password" placeholder="Password" onblur="loginCheck()">
<span id="login-status"></span>
</form>
</div>
<br>
<div class="registerCard">
<form action="scripts/signup.php" method="post" class="input-field" oninput="checkInput()">
<input type="text" name="firstName" placeholder="First Name" id="first_name" class="validate" >
<input type="text" name="lastName" placeholder="Surname">
<input type="text" nenter code hereame="username" id="username" placeholder="Username" onkeyup="UserAvailability()">
<span id="user-availability-status"></span>
<input type="email" name="email" id="email" placeholder="Email" onkeyup="EmailAvailability()">
<span id="email-availability-status"></span>
<input type="password" name="password" id="password1" placeholder="Password">
<input type="password" name="passwordVerify" id="password2" placeholder="Re-enter Password" onkeyup="passwordCheck()">
<span id="password-status"></span><br>
<span id="register-button"></span>
</div>
</div>
</div>
</body>
The way you are doing it, when these POST params are empty, the variable was never initialized.
A variable that will be used further down and not just inside this if-statement, should have its initial default value initialized outside all the if-statements.
Change
if(!empty($_POST["username"])) {
$usernameAuth = false;
to
$usernameAuth = false;
if(!empty($_POST["username"])) {
AND
if(!empty($_POST["email"])) {
$emailAuth = false;
to
$emailAuth = false;
if(!empty($_POST["email"])) {
AND
if(!empty($_POST["password1"]) && !empty($_POST["password2"])) {
$passAuth = false;
to
$passAuth = false;
if(!empty($_POST["password1"]) && !empty($_POST["password2"])) {
Or even better yet, initialize the initial default value of all these flags at the top of the file:
$usernameAuth = false;
$emailAuth = false;
$passAuth = false;
...
if(!empty($_POST["username"])) {
...
if(!empty($_POST["email"])) {
...
if(!empty($_POST["password1"]) && !empty($_POST["password2"])) {
That will make the logic much cleaner to follow, and leave less room for a mistake.
And then check for more of these oversights.

php call function from another class

I am trying to call a function with arguments from another class. The class with the function I need to call is auth.class.php (it's pretty long so I've shorten to the relevant class). I've a index.php file with jQuery form that when post calls reg.php and sends data their. I want to call the register function in auth.class.php file from the reg.php
I am not sure what I am doing wrong, I think the ajax might be the problem but any help will be appreciated.
auth.class.php
<?php
class Auth {
public function register($email, $username, $password, $repeatpassword)
{
$return = array();
$return['code'] = 400;
if ($this->isBlocked()) {
$return['code'] = 0;
return $return;
} else {
$validateEmail = $this->validateEmail($email);
$validateUsername = $this->validateUsername($username);
$validatePassword = $this->validatePassword($password);
if ($validateEmail['error'] == 1) {
$return['message'] = $validateEmail['message'];
return $return;
} elseif ($validateUsername['error'] == 1) {
$return['message'] = $validateUsername['message'];
return $return;
} elseif ($validatePassword['error'] == 1) {
$return['message'] = $validatePassword['message'];
return $return;
} elseif($password !== $repeatpassword) {
$return['message'] = "password_nomatch";
return $return;
} else {
if (!$this->isEmailTaken($email)) {
if (!$this->isUsernameTaken($username)) {
$addUser = $this->addUser($email, $username, $password);
if($addUser['error'] == 0) {
$return['code'] = 200;
$return['message'] = "register_success";
return $return;
} else {
$return['message'] = $addUser['message'];
return $return;
}
} else {
$this->addAttempt();
$this->addNewLog("", "REGISTER_FAIL_USERNAME", "User attempted to register new account with the username : {$username} -> Username already in use");
$return['message'] = "username_taken";
return $return;
}
} else {
$this->addAttempt();
$this->addNewLog("", "REGISTER_FAIL_EMAIL", "User attempted to register new account with the email : {$email} -> Email already in use");
$return['message'] = "email_taken";
return $return;
}
}
}
}
}
This is my html file index.php I am using jQuery mobile with ajax
<!DOCTYPE html>
<html>
<head>
<title>
Submit a form via AJAX
</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a4/jquery.mobile-1.0a4.min.css" />
<script src="http://code.jquery.com/jquery-1.5.2.min.js">
</script>
<script src="http://code.jquery.com/mobile/1.0a4/jquery.mobile-1.0a4.min.js">
</script>
</head>
<body>
<script>
function onSuccess(data, status)
{
data = $.trim(data);
$("#notification").text(data);
}
function onError(data, status)
{
// handle an error
}
$(document).ready(function()
{
$("#submit").click(function()
{
var formData = $("#Register").serialize();
$.ajax(
{
type: "POST",
url: "reg.php",
cache: false,
data: formData,
success: onSuccess,
error: onError
});
return false;
});
});
</script>
<!-- call ajax page -->
<div data-role="page" id="callAjaxPage">
<div data-role="header">
<h1>
Call Ajax
</h1>
</div>
<div data-role="content">
<form id="Register">
<div data-role="fieldcontain">
<label for="Email">
eMail
</label>
<input type="email" name="email" id="email" value="" />
<br />
<label for="UserName">
User Name
</label>
<input type="text" name="username" id="username" value="" />
<br />
<label for="Password">
Password
</label>
<input type="password" name="password" id="password" value="" />
<br />
<label for="Confirmpassword">
Confirm Password
</label>
<input type="password" name="repeatpassword" id="repeatpassword" value="" />
<h3 id="notification">
</h3>
<button data-theme="b" id="submit" type="submit">
Submit
</button>
</div>
</form>
</div>
<div data-role="footer">
<h1>
GiantFlyingSaucer
</h1>
</div>
</div>
</body>
</html>
This is my the php file that's placing the call the auth.class.php function.
<?php
include_once "password.php";
require_once "auth.class.php";
$mail = $_POST[email];
$usn = $_POST[username];
$pswd = $_POST[password];
$cpswd = $_POST[repeatpassword];
$register = new Auth();
$register ->register($mail, $usn, $pswd, $cpswd);
echo $return;
?>
Make index.php all the code is here and ajax function also here and make calls.php which is call by ajax function and calls.php file call your class.auth.php file.
you didn't assign the value returned by your function to anything.
Try this:
$return= $register ->register($mail, $usn, $pswd, $cpswd);
echo $return;
Here's the updated code that fixed the problem. I wasn't passing the data as an array serializeArray and also made some changes in the reg.php class as well.
New index.php file
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery Mobile: Theme Download</title>
<link rel="stylesheet" href="themes/Carelincs.min.css" />
<link rel="stylesheet" href="themes/jquery.mobile.icons.min.css" />
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.3/jquery.mobile.structure-1.4.3.min.css" />
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.3/jquery.mobile-1.4.3.min.js"></script>
</head>
<body>
<script>
$(document).ready(function()
{
$("#submit").click(function()
{
var formData = $("#register").serializeArray();
$.ajax(
{
type: "POST",
url: "../pages/register.php",
cache: false,
data: formData,
success: onSuccess,
});
return false;
});
});
function onSuccess(data, status)
{
data = $.trim(data);
$("#message").text(data);
}
function onError(data, status)
{
//Handle error
}
</script>
<div data-role="page" data-theme="a">
<div data-role="header" data-position="inline">
<h1>Header</h1>
</div>
<div data-role="content" data-theme="a">
<form action="" method="POST" id="register">
<label for="email">Email:</label>
<input type="email" name="email" placeholder="eMail"/>
<br />
<label for="username">Username:</label>
<input type="text" name="username" placeholder="User Name"/>
<br />
<label for="password">Password:</label>
<input type="password" name="password" placeholder="Password"/>
<br />
<label for="confirm password">Confirm Password</label>
<input type="password" name="repeatpassword" placeholder="Confirm Password"/>
<br />
<button type="submit" id="submit">Submit</button>
</form>
<p id="message"></p>
</div>
</div>
</body>
</html>
new reg.php file I also added information to connect to database.
<?php
require_once("../auth/config.class.php");
require_once("../auth/auth.class.php");
$config = new Config;
$dbh = new PDO("mysql:host=" . $config-> dbhost . ";dbname=" . $config->dbname, $config->dbuser, $config->dbpass);
$auth = new Auth($dbh, $config);
$email = $_POST["email"];
$username = $_POST["username"];
$password = $_POST["password"];
$repeatpassword = $_POST["repeatpassword"];
$register = $auth->register($email, $username, $password, $repeatpassword );
// Temporary just to see what's going on :
var_dump($register);
?>

jquery-mobile ajax runs one more time after every failed pass

I have my html page where people can sign up, which calls my php page for checks and inputs to db,
If i get an error, for example someone does not select their gender it alerts the user as it should. Problem is if the user does not select there gender and submits again the ajax is called twice now and i get two of the same alert messages, If done once more i get three alert messages and this contiunes growing on every press etc. How can i stop this happening.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<title>
</title>
<link rel="stylesheet" href="css/logout-button.min.css" />
<link rel="stylesheet" href="css/jquery.mobile-1.3.0.min.css" />
<link rel="stylesheet" href="css/my.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</script>
<script src="js/jquery.mobile-1.3.0.min.js"></script>
<script src="js/jquery.cookies.2.2.0.min.js"></script>
<script src="js/account-login.js"></script>
</head>
<body>
<!-- Home -->
<div data-role="page" id="account-signup">
<script>
function submitForm() {
$(document).ready(function() {
$("form#signupForm").submit(function() {
var form_data = $('#signupForm').serialize();
$.ajax({
type: "POST",
url: "ajaxResponder.php",
dataType: 'html',
data: form_data,
complete: function(data){
if(data.responseText == 'yes'){
alert("Your Account has been created");
$.mobile.changePage( "account-login.html", { transition: "slide"} );
}else {
alert(data.responseText);
}
}
});
return false;
});
});
}
</script>
<div data-theme="a" data-role="header">
<a data-role="button" href="account-login.html" data-transition="slide"
data-icon="arrow-l" data-iconpos="left" class="ui-btn-left">
Back
</a>
<h3>
Sign-Up
</h3>
</div>
<div data-role="content">
<form id="signupForm" name="signupForm">
<input name="method" id="method" placeholder="method" value="account-signup" type="hidden" />
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<label for="forename">
Forename *
</label>
<input name="forename" id="forename" placeholder="Forename" value="" type="text" />
</fieldset>
</div>
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<label for="surname">
Surname *
</label>
<input name="surname" id="surname" placeholder="Surname" value="" type="text" />
</fieldset>
</div>
<div data-role="fieldcontain">
<label for="gender">Gender</label>
<select name="gender" id="gender" data-native-menu="false">
<option>Gender</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</div>
<div data-role="fieldcontain">
<script type="text/javascript">
$(function(){
var items="";
$.getJSON("ajaxResponder.php?method=account-signup-countries",function(data){
items+='<option value="Select Country">Select Country</option>';
$.each(data,function(index,item)
{
items+="<option value='"+item.id+"'>"+item.name+"</option>";
});
$("#countries").html(items);
$("#countries").trigger("change");
});
});
</script>
<legend>Country *</legend>
<select name="countries" id="countries" data-native-menu="false">
</select>
</div>
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<label for="email">
Email *
</label>
<input name="email" id="email" placeholder="Email" value="" type="text" />
</fieldset>
</div>
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<label for="password">
Password *
</label>
<input name="password" id="password" placeholder="Password" value="" type="password" />
<label for="confirm">
Confirm Password *
</label>
<input name="confirm" id="confirm" placeholder="Confirm" value="" type="password" />
</fieldset>
</div>
<input data-theme="b" value="Sign-Up" type="submit" onclick="submitForm()" />
</form>
</div>
</div>
</body>
</html>
my php
case 'account-signup':
$password_minlength = 6;
$password_maxlength = 40;
$message == "";
function validusername($username) {
$allowedchars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ'";
for ($i = 0; $i < strlen($username); ++$i)
if (strpos($allowedchars, $username[$i]) === false)
return false;
return true;
}
$forename= $_POST["forename"];
$surname= $_POST["surname"];
$email= $_POST["email"];
$password= $_POST["password"];
$confirm= $_POST["confirm"];
$day = $_POST["select-choice-day"];
$month = $_POST["select-choice-month"];
$year = $_POST["select-choice-year"];
$country = $_POST["countries"];
$gender = $_POST["gender"];
if ($day =='Day' or $month == 'Mon' or $year =='Year')
$message = "You Need to fill in Your DOB";
if ($gender =='Gender')
$message ="Please select your Gender";
if ($country == "Select Country")
$message ="Please select a Country";
if (empty($password) || empty($forename) || empty($surname) || empty($email) || empty($confirm) )
$message = "All fields required to be filled in";
elseif ($password != $confirm)
$message = "Your passwords do not match";
elseif (strlen($password) < $password_minlength)
$message = sprintf("Your password needs to be more than $password_minlength char");
elseif (strlen($password) > $password_maxlength)
$message = sprintf("Your password needs to be less than $password_maxlength char");
elseif (!validusername($forename))
$message = "Invalid characters used in your forename";
elseif (!validusername($surname))
$message = "Invalid characters used in your surname";
elseif (!validemail($email))
$message = "A Valid email address is required";
if ($message == "") {
// check if email addy is already in use
$a = (#mysql_fetch_row(#SQL_Query_exec("select count(*) from users where email='$email'")));
if ($a[0] != 0)
$message = "Email Address $email has already signed up. Please use account-recovery ";
}
if ($message == "") {
$signupclass = '1';
$status = "confirmed";
$dob = "$year-$month-$day";
$secret = mksecret(); //generate secret field
$password = passhash($password);// hash the password
$forename1 = str_replace('\' ', '\'', ucwords(str_replace('\'', '\' ', strtolower($forename))));
$surname1 = str_replace('\' ', '\'', ucwords(str_replace('\'', '\' ', strtolower($surname))));
SQL_Query_exec("INSERT INTO users (forename,surname, password, secret, email, status, added, last_access, country, gender,dob, stylesheet, language, class, ip) VALUES (" .
implode(",", array_map("sqlesc", array($forename1,$surname1, $password, $secret, $email, $status, get_date_time(), get_date_time(), $country, $gender,$dob, $site_config["default_theme"], $site_config["default_language"], $signupclass, getip()))).")");
$message="yes";
}
echo "$message";
break;
You have an error in your javascript, when calling function, you don't need these lines:
$(document).ready(function() {
$("form#signupForm").submit(function() {
First of all you dont need document ready because you are not waiting for that state. Second thing, if you are using inline hjavascript with onclick=... you dont need to bind a submit event to the form.
Basically each time you call in again you are binding submit event to the form.
Third thing, this would not happen if validation was implemented on a client side, so think about that. You can easily implement jQuery Validate plugin.
My advice to you would be, remove onclick event from this line:
<input data-theme="b" value="Sign-Up" type="submit" onclick="submitForm()" />
Remove onclick function and just use everything like this:
$(document).ready(function() {
$('#signupForm').off('submit').on('submit',function(e) {
var form_data = $('#signupForm').serialize();
$.ajax({
type: "POST",
url: "ajaxResponder.php",
dataType: 'html',
data: form_data,
complete: function(data){
if(data.responseText == 'yes'){
alert("Your Account has been created");
$.mobile.changePage( "account-login.html", { transition: "slide"} );
}else {
alert(data.responseText);
}
}
});
return false;
});
});
Because of submit event this code will trigger when you press submit button, no need for onclick. And notice how submit is handled now:
$('#signupForm').off('submit').on('submit',function(e) {
This will prevent multiple submit events from happening.

Categories