JQuery Mobile - Registration Form - The JS cannot call the php - javascript

I have created a registration form, but the js file cannot call the php.
Are there anyone can give me some advise?
My question is when I click the submit button, there is no reaction. Do I have any mistakes? Thanks
<!DOCTYPE html>
<html>
<head>
<meta name="robots" content="noindex, nofollow">
<title>Tittle</title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<script type="text/javascript" src="js/registration.js"></script>
<link href="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.css"
rel="stylesheet" type="text/css"/>
<script src="http://code.jquery.com/jquery-1.6.4.min.js"
type="text/javascript"></script>
<script src="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.js"
type="text/javascript"></script>
<script type="text/javascript" src="js/registration1.js"></script>
<script type="text/javascript">
$(document).on("mobileinit", function() {
$.extend( $.mobile , {
pageLoadErrorMessage: 'Either the page cannot be found or it cannot
be loaded.'
});
});
$(document).on("pageinit","#page", function() {
alert("pageinit is bound!");
});
</script>
</head>
<body>
<div class="container">
<div class="main">
<div data-role="header">
<h1>Register</h1>
</div>
<form class="form" method="post" action="#">
<label>Name :</label>
<input type="text" name="dname" id="name">
<label>Email :</label>
<input type="text" name="demail" id="email">
<label>Password :</label>
<input type="password" name="password" id="password">
<label>Confirm Password :</label>
<input type="password" name="cpassword" id="cpassword">
<button type="button" name="register" id="register"
class="btn">Submit</button>
</form>
</div>
</div>
<div data-role="footer">
<h4>Footer</h4>
</div>
</body>
</html>
Below is the JS
$(document).ready(function () {
$("#register").click(function () {
var name = $("#name").val();
var email = $("#email").val();
var password = $("#password").val();
var cpassword = $("#cpassword").val();
if (name == '' || email == '' || password == '' || cpassword == '') {
alert("Please fill all fields...!!!!!!");
} else if ((password.length) < 8) {
alert("Password should atleast 8 character in length...!!!!!!");
} else if (!(password).match(cpassword)) {
alert("Your passwords don't match. Try again?");
} else {
$.post("register.php", {
name1: name,
email1: email,
password1: password
}, function (data) {
if (data == 'You have Successfully Registered.....') {
$("form")[0].reset();
}
alert(data);
});
}
});
});
Below is the PHP
$hostname = "127.0.0.1";
$username = "root";
$password = "123456";
$connection = mysql_connect($hostname, $username, $password) or die("Could
not open connection to database");
$db = mysql_select_db("mydb", $connection); // Selecting Database.
$name=$_POST['name1'];
$email=$_POST['email1'];
$password= sha1($_POST['password1']);
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
echo "Invalid Email.......";
}
else{
$result = mysql_query("SELECT * FROM registration WHERE email='$email'");
$data = mysql_num_rows($result);
if(($data)==0){
$query = mysql_query("insert into registration(name, email, password) values
('$name', '$email', '$password')"); // Insert query
if($query){
echo "Successfully Registered";
}
else
{
echo "Error";
}
}
else{
echo "This email is already registered. Please try again";
}
}
mysql_close ($connection);
?>

Your form action is empty try changing action="#" to action="register.php"

Related

Run PHP after JS validation

I am doing email validation for admin registration using JavaScript and save the data to database using PHP. Supposedly, the registration is done only if the email is valid. But when the email evaluates to invalid, the PHP code still run. How do I do it so that when the email is invalid, the PHP won't run.
Below is the PHP code to save data to database:
<?php
include('connection.php');
if(isset($_POST['saveBtn']))
{
$name = $_POST['name'];
$ic = $_POST['ic'];
$email = $_POST['email'];
$pass = $_POST['pass'];
$dob = $_POST['dob'];
$contact = $_POST['contact'];
$gender = $_POST['gender'];
$des = $_POST['des'];
$address = $_POST['address'];
// Check if data exist
$check = "SELECT * FROM admin WHERE admEmail = '".$email."' AND admPassword = '".$pass."'";
if(mysqli_num_rows(mysqli_query($connect,$check)) > 0)
{
?>
<script>
alert('This email and password already registered!');
</script>
<?php
}
else
{
$insert = "INSERT INTO admin (admName, admIC, admEmail, admPassword, admDOB, admContact, admGender, admDesignation, admAddress, admDateJoin) VALUES ('".$name."', '".$ic."', '".$email."', '".$pass."', '".$dob."', '".$contact."', '".$gender."', '".$des."', '".$address."', NOW())";
if(mysqli_query($connect, $insert))
{
?>
<script>
alert('Insertion Successful!');
window.close();
window.opener.location.reload();
</script>
<?php
}
else
{
?>
<script>
alert('Insertion Failed. Try Again!');
</script>
<?php
}
}
}
?>
Below is the JS:
function validateEmail() {
var email = document.addAdminForm.email.value;
var validRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
if (email.match(validRegex))
{
alert("Valid email address!");
return true;
}
else
{
document.getElementById("email_error").innerHTML = "Invalid email";
document.addAdminForm.email.focus();
return false;
}
}
Below is the partial HTML form:
<form class="w-100" name="addAdminForm" method="POST" onsubmit="validateEmail(this)" action="add_admin.php">
<div class="row">
<div class="col form-group">
<!-- <label for="email">Email</label> -->
<input type="text" class="form-control" name="email" placeholder="Email" required>
<span class="error email_error" id="email_error"></span>
</div>
<div class="float-right">
<input type="submit" class="btn button_primary" value="Save" name="saveBtn">
</div>
</form>
I expect PHP run when validation is true
add this:
onsubmit="return validateEmail(this)"
change your JS code to:
var validRegex = /^([a-zA-Z0-9_-])+#([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;

Problem with register form using JavaScript validation and PHP

I have a problem. I don't know why when I did run the HTML and javascript only (without PHP part), the validation works really well. However, when I did run the PHP with the HTML and JavaScript, the validation doesn't work. For example, when the username is 123john (everything else such as password, name,... met the requirements) which is not allowed. The form still submitted successfully (I did check the MySQL database and the user 123john is there). Can someone help me with this? Thank you for your help.
The original code structure is the PHP and HTML are in the same file, only the JavaScript is on a separate file.
<?php
session_start();
require 'connect.php';
if(isset($_POST['register'])){
$username = !empty($_POST['user_name']) ? trim($_POST['user_name']) : null;
$pass = !empty($_POST['pass']) ? trim($_POST['pass']) : null;
$firstName = !empty($_POST['first_name']) ? trim($_POST['first_name']) : null;
$lastName = !empty($_POST['last_name']) ? trim($_POST['last_name']) : null;
$collegeName = !empty($_POST['uni']) ? trim($_POST['uni']) : null;
$majorName = !empty($_POST['major']) ? trim($_POST['major']) : null;
$sql = "SELECT COUNT(user_name) AS num FROM users WHERE user_name = :username";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':username', $username);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($row['num'] > 0){
die('Username existed');
}
$sql = "INSERT INTO users (user_name, pass, first_name, last_name, uni, major) VALUES (:username, :password, :first_name, :last_name, :uni, :major)";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':username', $username);
$stmt->bindValue(':password', $pass);
$stmt->bindValue(':first_name', $firstName);
$stmt->bindValue(':last_name', $lastName);
$stmt->bindValue(':uni', $collegeName);
$stmt->bindValue(':major', $majorName);
$result = $stmt->execute();
if($result){
echo 'Thank you for registering with our website.';
}
}
?>
var check_form=document.getElementById("registration");
var pattern=/^[a-zA-Z\s]+$/;
var patternUsername=/^[A-Za-z]\w*$/;
function check(event){
var userName=document.getElementById("username");
var passWord=document.getElementById("password");
var last_name=document.getElementById("lastName");
var first_name=document.getElementById("firstName");
var collegeName=document.getElementById("uni");
var majorName=document.getElementById("majoring");
event.preventDefault();
if(userName.value==""){
alert("User name needs to be specified");
userName.focus();
}
else{
if(!patternUsername.test(userName.value)){
alert("Invalid username");
userName.focus();
}
}
if(passWord.value==""){
alert("Password needs to be specified");
passWord.focus();
}
else{
if(passWord.length<8){
alert("Password needs to be longer than 8 characters");
passWord.focus();
}
}
if(first_name.value==""){
alert("First name needs to be specified");
first_name.focus();
}
else{
if(!pattern.test(first_name.value)){
alert("First name does not allow number");
first_name.focus();
}
}
if(last_name.value==""){
alert("Last name needs to be specified");
last_name.focus();
}
else{
if(!pattern.test(last_name.value)){
alert("Last name does not allow number");
last_name.focus();
}
}
if(collegeName.value==""){
alert("College name needs to be specified");
collegeName.focus();
}
else{
if(!pattern.test(collegeName.value)){
alert("Invalid college name");
collegeName.focus();
}
}
if(majorName.value==""){
alert("Major name needs to be specified");
majorName.focus();
}
else{
if(!pattern.test(majorName.value)){
alert("Invalid major name");
majorName.focus();
}
}
/*
if(first_name.value!=="" && last_name.value!==""&&email!==""&&pattern.test(first_name.value)&&pattern.test(last_name.value)){
alert("Perfect");
}
*/
}
check_form.addEventListener("submit",check);
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Register</title>
<!--<link rel="stylesheet" href="./register.css">-->
<script src="./script.js" defer></script>
<style>
form div{
padding: 8px;
}
</style>
<link href="https://fonts.googleapis.com/css2?family=PT+Sans&display=swap" rel="stylesheet">
</head>
<body>
<h1>Register</h1>
<form id="registration" action="register.php" method="post">
<div id='userName'>
<label for="username">Username: </label>
<input type="text" id="username" name="user_name"><br>
</div>
<div id="passWord">
<label for="password">Password: </label>
<input type="text" id="password" name="pass"><br>
</div>
<div id='firstname'>
<label for="firstName">First Name: </label>
<input type="text" id="firstName" name="first_name"><br>
</div>
<div id="lastname">
<label for="lastName">Last Name: </label>
<input type="text" id="lastName" name="last_name"><br>
</div>
<div id="uniName">
<label for="uni">College Name: </label>
<input type="text" id="uni" name="uni"><br>
</div>
<div id="majorName">
<label for="majoring">Major: </label>
<input type="text" id="majoring" name="major"><br>
</div>
<br>
<input type="submit" name="register" value="Register"><br><br>
Already have an account?
</form>
</body>
</html>
If you want to do your client-side validation. you must change the type of the button from (send) to (button). Then, create a function in JS to validate your form.
Call the function by clicking onclick button = "ItsFunctionForValidateAndSubmit ()".
After checking: Create a form submission method using javascript.
Here is a link to some sample form submissions.
Send POST data using XMLHttpRequest
<input type="buttom" name="register" value="Register" onclick="ItsFunctionForValidateAndSubmit()">

jQuery PHP Post

I got a problem maybe is simple but dont know how to load jquery_post.php when I send the data for jquery_send.php I resume I send information from jquery_send.php to jquery_post.php and I want that after send the page jquery_post.php load with the data
This is what I have in jquery_send.php:
<html>
<head>
<link href='http://fonts.googleapis.com/css?
family=Source+Sans+Pro|Open+Sans+Condensed:300|Raleway' rel='stylesheet' type='text/css'>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
<script>
$(document).ready(function(){
$("#btn").click(function(){
var vname = $("#name").val();
var vemail = $("#email").val();
if(vname=='' && vemail=='')
{
alert("Please fill out the form");
}
else if(vname=='' && vemail!==''){alert('Name field is required')}
else if(vemail=='' && vname!==''){alert('Email field is required')}
else{
$.post("jquery_post.php",
{
name:vname,
email:vemail
},
function(response,status){
alert("*----Received Data----*nnResponse : " + response+"nnStatus : " + status);
$("#form")[0].reset();
});
}
});
});
</script>
</head>
<body>
<div id="main">
<h2>jQuery Ajax $.post() Method</h2>
<hr>
<form id="form" method="post">
<div id="namediv"><label>Name</label>
<input type="text" name="name" id="name" placeholder="Name"/><br></div>
<div id="emaildiv"><label>Email</label>
<input type="text" name="email" id="email" placeholder="Email"/></div>
</form>
<button id="btn">Send Data</button>
</div>
</body>
</html>
and in jquery_post.php I have this:
<?php
if($_POST["name"])
{
$name = $_POST["name"];
$email = $_POST["email"];
echo "Welcome ". $name ."!";
?>
It works just fine, but you have a syntax error in you jquery_post.php
<?php
if($_POST["name"])
{
$name = $_POST["name"];
$email = $_POST["email"];
echo "Welcome ". $name ."!";
} // you missed this
?>
it was returning Parse error: syntax error, unexpected end of file
Please try, this may help
<html>
<head>
<link href='http://fonts.googleapis.com/css?
family=Source+Sans+Pro|Open+Sans+Condensed:300|Raleway' rel='stylesheet' type='text/css'>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
<script>
$(document).ready(function(){
$("#btn").click(function(){
var vname = $("#name").val();
var vemail = $("#email").val();
if(vname=='' && vemail=='')
{
alert("Please fill out the form");
}
else if(vname=='' && vemail!==''){alert('Name field is required')}
else if(vemail=='' && vname!==''){alert('Email field is required')}
else{
$.post("post.php",
{
name:vname,
email:vemail
},
function(response,status){
alert("*----Received Data----*nnResponse : " + response+"nnStatus : " + status);
$("#form")[0].reset();
window.location.href = 'post.php';
});
}
});
});
</script>
</head>
<body>
<?php session_start(); ?>
<div id="main">
<h2>jQuery Ajax $.post() Method</h2>
<hr>
<form id="form" method="post">
<div id="namediv"><label>Name</label>
<input type="text" name="name" id="name" placeholder="Name"/><br></div>
<div id="emaildiv"><label>Email</label>
<input type="text" name="email" id="email" placeholder="Email"/></div>
</form>
<button id="btn">Send Data</button>
</div>
</body>
</html>
And in jquery_post.php I have made some changes When you post data to jquery_post.php it will create a session named "user" you can retrieve name any time from the session as I did.
<?php
session_start();
if(isset($_POST["name"]))
{
$_SESSION['user'] = $_POST["name"];
$name = $_POST["name"];
$email = $_POST["email"];
}
echo "Welcome ". $_SESSION['user'] ."!";
?>

Insert data into MySQL database from Javascript calling PHP file

I have the below code which calls a .php file to insert data into a MySQL database, but cant seem to get the .php file to run. Any suggestions?
I am very new to script so i am trying this registration form example. The database, 'college', with its table, 'registration', seems to be fine, but no php code executes. It must be something really simple but i cant seem to work it out?
$(document).ready(function() {
$("#register").click(function() {
var name = $("#name").val();
var email = $("#email").val();
var password = $("#password").val();
var cpassword = $("#cpassword").val();
if (name == '' || email == '' || password == '' || cpassword == '') {
alert("Please fill all fields...!!!!!!");
} else if ((password.length) < 8) {
alert("Password should atleast 8 character in length...!!!!!!");
} else if (!(password).match(cpassword)) {
alert("Your passwords don't match. Try again?");
} else {
//alert(name); //This line reads fine
$.post("register.php",
{
name1: name,
email1: email,
password1: password
},
function(data) {
if (data == 'You have Successfully Registered.....') {
$("form")[0].reset();
}
alert(data);
});
}
});
});
<?php
$connection = mysql_connect("localhost", "root", "Winchester12"); // Establishing connection with server..
$db = mysql_select_db("college", $connection); // Selecting Database.
$name=$_POST['name1']; // Fetching Values from URL.
$email=$_POST['email1'];
echo $email;
$password= sha1($_POST['password1']); // Password Encryption, If you like you can also leave sha1.
// Check if e-mail address syntax is valid or not
$email = filter_var($email, FILTER_SANITIZE_EMAIL); // Sanitizing email(Remove unexpected symbol like <,>,?,#,!, etc.)
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
echo "Invalid Email.......";
}else{
$result = mysql_query("SELECT * FROM registration WHERE email='$email'");
$data = mysql_num_rows($result);
if(($data)==0){
$query = mysql_query("insert into registration(name, email, password) values ('$name', '$email', '$password')"); // Insert query
if($query){
echo "You have Successfully Registered.....";
}else
{
echo "Error....!!";
}
}else{
echo "This email is already registered, Please try another email...";
}
}
mysql_close ($connection);
?>
<!DOCTYPE html>
<html>
<head>
<title>Squash Registration Form</title>
<meta name="robots" content="noindex, nofollow">
<!-- Include CSS File Here -->
<link rel="stylesheet" href="style.css"/>
<!-- Include JS File Here -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="registration.js"></script>
</head>
<body>
<div class="container">
<div class="main">
<form class="form" method="post" action="#">
<h2>Squash Registration Form</h2>
<label>Name :</label>
<input type="text" name="dname" id="name">
<label>Email :</label>
<input type="text" name="demail" id="email">
<label>Password :</label>
<input type="password" name="password" id="password">
<label>Confirm Password :</label>
<input type="password" name="cpassword" id="cpassword">
<input type="button" name="register" id="register" value="Register">
</form>
</div>
</body>
</html>
It could be a path related issue.
you might want to review the path to the register.php file to be sure its in the right place.
It seems that nothing is passed to register.php file. Please try with 'ajax' instead of jquery post.

web page accessible by user authorized/unauthorized and causes error

My page is main.php it was made like this code
<?php
include_once('createtables.php');
include('function.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../includes/css/bootstrap.min.css">
<link rel="stylesheet" href="../includes/css/main.css">
<script src="../includes/js/jQuery.js"></script>
<script src="../includes/js/login.js"></script>
<script src="../includes/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container-fluid">
<form id="lgform" action="checklogin.php" method="post">
<h4 class="text-primary" id="llc"><img src="../includes/img/chatballoon.png"> Network Chat </h4>
<div class="input-group" id="firstone">
<span class="input-group-addon">
<span class="glyphicon glyphicon-user"></span>
</span>
<input type="text" class="form-control" placeholder="Enter Account name" id="username" name="username" autofocus>
</div>
<div class="input-group" id="secondtwo">
<span class="input-group-addon" id="password-addon">
<span class="glyphicon glyphicon-lock"></span>
</span>
<input type="password" class="form-control" placeholder="Enter your password" aria-decribedby="password-addon" id="password" name="password" autofocus>
</div>
Create Account
<input type="submit" class="pull-right btn btn-primary btn-sm" name="submit" id="submit" value="Enter now">
</form>
</div>
</body>
</html>
This is my checklogin php was like this:
<?php
ob_start();
session_start();
include("function.php");
$conn = new Functions();
$conn = $conn->db;
//define username and password
$username = $_POST['username'];
$password = $_POST['password'];
$username = stripslashes($username);
$password = stripcslashes($password);
$salt = "dctech2015ABcRXd";
$password = md5($password) . $salt;
$password = sha1($password);
//SELECT QUERY TO FIND IF INPUT INFORMATION WAS ON DATABASE
$stmt = $conn->query("SELECT * FROM users WHERE username ='$username' AND password='$password'");
//LOOP ENTIRE DATABASE ROW
$count = $stmt->rowCount();
//IF INFORMATION FOUND SELECT STATUS IF ALREADY ONLINE OR NOT
if($count == 1){
$status;
$stmt = $conn->prepare("SELECT status FROM users WHERE username='$username'");
$stmt->execute();
while($checkstatus = $stmt->fetch(PDO::FETCH_OBJ)){
$status = $checkstatus->status;
}
if($status == 'Online'){
echo "online";
}else{
echo "success";
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
$stmt = $conn->prepare("UPDATE users SET status='Online' WHERE username='$username'");
$stmt->execute();
}
}
ob_end_flush();
?>
ajax here:
$(document).ready(function(){
$("#submit").click(function(e){
e.preventDefault();
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if(username==""){
alert("Please enter your account name");
}else if(password == ""){
alert("Please enter your password");
}else{
$.ajax({
type: "POST",
url: "checklogin.php",
data: "username="+username+"&password="+password,
success: function(data){
if(data == "success"){
window.location.href="chat.php";
}
else if(data == "online"){
alert("account is already online");
}else{
alert("Invalid Account name/Account password");
}
},error:function(data){
alert("an error occured through data");
}
});
}
document.getElementById("username").value = "";
document.getElementById("password").value = "";
});
return false;
});
problem that checklogin.php file is accessible to browser. what i want is to avoid unauthorized users to go to this page cause even login users if they type on browser register.php it will go to it and says username error etc.
This type of error:
You should respond with the standard http status code: 401, so the browser knows it has failed to load the page:
if($count == 1){
...
} else {
header("HTTP/1.1 401 Unauthorized");
// or for php 5.4:
http_response_code(401);
}
Update:
For the errors you added later:
Before you access the values in $_POST, check if they are present:
if (isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
// ... all the rest of your code that depends on $_POST comes here
}
You can add some checking to your check_login script to see if the URL matches and kick it back. if(strpos($_SERVER['REQUEST_URI'], 'register.php')) exit() or something to that affect.

Categories

Resources