I'm pretty new to Javascript and PHP, but need to do a form validation for the user registration and I'm having trouble inserting the new user into the database.
I validate the form on the client side via JQuery's validation plugin and try to send a request to the database where I check the user availability via AJAX. The validation plugin works but something goes wrong when I requesting the database entries via AJAX, because if I press the "Send" button in the form I get the Error occurred alert on screen.
My registration.html code:
<form id="form" name="registration" action="" method="POST">
<label for="user_name">Nickname:</label><br>
<input type="input" size="40" maxlength="10" name="user_name" id="user_name" placeholder="Nickname"><br><br>
<label for="user_email">Email:</label><br>
<input type="email" size="40" maxlength="20" name="user_email" id="user_email" placeholder="Email address"><br><br>
<label for="user_password">Password:</label><br>
<input type="password" size="40" maxlength="50" name="user_password" id="user_password" placeholder="Passwort"><br>
<label for="confirmed_password">Confirm password:</label><br>
<input type="password" size="40" maxlength="50" name="confirmed_password" id="confirmed_password" placeholder="Passwort bestätigen"><br><br>
<input type="submit" name="register" value="Send">
</form>
<script src="./form_validation.js"></script>
My form_validation.js code:
$("#form[name='registration']").validate({
rules: {
user_name: {
required: true
},
user_email: {
required: true,
email: true
},
user_password: {
required: true,
minlength: 7
},
confirmed_password: {
required: true,
equalTo: "#user_password"
}
},
messages: {
user_name: 'Enter a nickname.',
user_email: {
required: 'Enter your email address.',
email: 'Enter a valid email address.',
},
user_password: {
required: 'Enter a password.',
minLength: 'At least 7 characters.',
},
confirmed_password: {
required: 'Confirm password.',
equalTo: 'Passwords have to match.',
}
},
submitHandler: function (form) {
$.ajax({
url:'./user.php',
type: "post",
data: $(form).serialize(),
success: function() {
alert("success");
console.log();
$("#result").html('Submitted');
},
error: function() {
alert("Error occured");
console.log();
$("#result").html('An error occured while submitting.');
}
});
}
});
});
My user.php code:
<?php
require_once __DIR__ . "./connection.php";
if (isset($_POST["register"]) && isset($_POST['user_name']) && isset($_POST['user_email']) && isset($_POST['user_password']) && isset($_POST['confirmed_password']))
{
$user_name = $_POST['user_name'];
$user_email = $_POST['user_email'];
$user_password = $_POST['user_pasword'];
$db = new DB_connection;
$sql = "SELECT * FROM user WHERE user_name = :user_name OR user_email = :user_email";
$statement = $db->conn->prepare($sql);
$statement->bindParam("user_name", $user_name);
$statement->bindParam("user_email", $user_email);
if ($statement->execute())
{
$sql = "INSERT INTO user (user_name, user_pass, user_email) VALUES (:user_name, :user_password, :user_email)";
$stmt = $db->conn->prepare($sql);
$stmt->bindParam(":user_name", $user_name);
$stmt->bindParam(":user_password", $user_password);
$stmt->bindParam(":user_email", $user_email);
if ($stmt->execute()) {
echo "New user inserted";
} else {
echo "Something went wrong!";
}
} else {
echo "Error!";
}
}
Found the solution. I just had to replace the include_once __DIR__ './connection.php'; with include_once __DIR__ '/../config/config.php';. What is strange is that no MYSQL error message appeared and other classes work without the include_once statement.
Related
Using jQuery validation plugin, I have been trying to validate and submit my form. JS code for this as shown below.
jQuery.validator.addMethod(
"regex",
function(value, element, regexp) {
var re = new RegExp(regexp);
return this.optional(element) || re.test(value);
},
"Enter a valid phone number."
);
var phoneNumbers_default = {
maxlength: 11,
regex: /^0+\d{2}[ -]\d{7}( x\d{1,6})?$/,
remote: "./includes/check-duplicate-mobile.php"
// remote: {
// url: "./includes/check-duplicate-mobile.inc.php",
// type: "post"
// }
};
var phoneNumbers_required = {
required: true
};
var phoneNumber_message = {
minlength: "Your mobile number should be at least 11 digits long.",
maxlength: "Your mobile number cannot be longer than 11 digits.",
remote: "One active user account already exists for this mobile number. Duplicates are not allowed."
}
jQuery.extend(phoneNumbers_default,phoneNumbers_required);
function processForms(el,fileAttached=false) {
var $el = $('#'+el)
$el.validate({
errorElement: 'span',
focusInvalid: false,
//ignore: ".ignore",
ignore: "",
rules: {
email: {
required: true,
email: true
},
mobileNumber: phoneNumbers_default,
p_mobile: phoneNumbers_default,
},
messages: {
email: {
required: "Please provide a valid email.",
email: "Please provide a valid email."
},
mobileNumber:phoneNumber_message,
p_mobile:phoneNumber_message,
},
submitHandler: function (form) {
var $form = $(form);
var url = 'add_user_form.php';
var formData = new FormData(form);
$.ajax({
url: url,
type: "POST",
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(json) {
json = jQuery.parseJSON(json)
if (json.success) {
// it worked
} else {
// it not worked
}
},
});
return false;
}
})
}
Above code works fine for the first submit. I meant it is new form submission. But my problem is when I try to update the existing data using the same form it always checks remote method and become return ture. That means, if I want to update the existing data, I always have to change the mobile number.
UPDATE:
Form markup
<form class="mt-2 text-dark-m1" id="addNew_user" method="post" action="" >
<div class="form-group row">
<div class="col-sm-3 col-form-label text-sm-right pr-0">
Email:
</div>
<div class="col-sm-9">
<input type="text" name="principal_email" class="form-control col-sm-4" value="<?=$p_email?>" />
</div>
</div>
<div class="form-group required row">
<div class="col-sm-3 col-form-label text-sm-right pr-0">
Mobile :
</div>
<div class="col-sm-9">
<input type="text" name="p_mobile" class="form-control col-sm-4" value="<?=$p_mobile?>" required />
</div>
</div>
<div class="border-t-1 bgc-secondary-l4 brc-secondary-l2 py-35 mx-n25 mt-5">
<div class="offset-md-3 col-md-9 text-nowrap flex-align-center">
<button class="btn btn-info btn-bold px-4" type="submit"><i class="fa fa-check mr-1"></i>Submit</button>
</div>
</div>
</form>
Serverside Code:
$mobileNumber = isset($_GET['p_mobile']) ? $_GET['p_mobile'] : '';
if (strlen($mobileNumber) >= 10 && strlen($mobileNumber) <= 12) {
$sql ="SELECT user_id FROM user WHERE mobile = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$mobileNumber]);
$uid = $stmt->fetchColumn();
if ($uid) echo "false"; // it comes to this line
else echo "true";
} else {
echo "false";
}
Can anybody tell me, how I fix this issue?
What about making this change in the server side? I am still learning php, but i believe you will get the idea.
$mobileNumber = isset($_GET['p_mobile']) ? $_GET['p_mobile'] : '';
$requestUserId = isset($_GET['user_id']) ? $_GET['user_id'] : '';
if (strlen($mobileNumber) >= 10 && strlen($mobileNumber) <= 12) {
$sql ="SELECT user_id FROM user WHERE mobile = ?";
if (requestUserId) $sql += " AND user_id <> ?"
$stmt = $pdo->prepare($sql);
$stmt->execute([$mobileNumber, $requestUserId]);
$uid = $stmt->fetchColumn();
if ($uid) echo "false"; // it comes to this line
else echo "true";
} else {
echo "false";
}
I am trying to validate a form using jquery validation and I keep receiving an error "Uncaught TypeError: Cannot read property 'settings' of undefined".
The error is coming from the jquery-latest.min.js file and my jquery.validate.min.js file. Any suggestions on how to fix this?
Also, when I remove validationObj.form(); block, the error goes away, but then the validation rules are not running.
Here is my HTML:
<div id="contactForm">
<p>Contact Information</p></br>
<div id="contactInfo">
<label>First Name:</label>
<input type="text" name="fName" id="fName"/></br>
<label>Last Name:</label>
<input type="text" name="lName" id="lName"/></br>
<label>Email:</label>
<input type="text" name="email" id="email"/></br>
<label>Phone:</label>
<input type="text" name="phone" id="phone"/></br>
</div></br>
And here is my js:
var validationObj = $("#contactForm").validate
(
{
rules:
{
fName:{required:true},
lName:{required:true},
email:{required:true, email:true},
},//End rules
messages:
{
fName:{equalTo:"Please enter your first name"},
lName:{equalTo:"Please enter your last name"},
email:{minlength:"Please enter a valid email"},
},//End messages
errorPlacement:
function(error, element)
{
error.appendTo( element.next());
}
}//End validationObj
);//End var validationObj
validationObj.form();
$("form").submit
(function(e)
{
if(!validationObj.form())
{
alert("Form Errors");
}
}
);
}
Wrapped it in a form and removed the call before the submit. Working fiddle.
var validationObj = $("#contactForm").validate({
rules: {
fName: {
required: true
},
lName: {
required: true
},
email: {
required: true,
email: true
},
}, //End rules
messages: {
fName: {
equalTo: "Please enter your first name"
},
lName: {
equalTo: "Please enter your last name"
},
email: {
minlength: "Please enter a valid email"
},
}, //End messages
errorPlacement: function(error, element) {
error.appendTo(element.next());
}
} //End validationObj
); //End var validationObj
$("#contactForm").submit(function(e) {
if (!validationObj.form()) {
alert("Form Errors");
} else {
alert("Form Valid");
}
});
I want to check to see if an email already exists in a table or not.
I am using bootstrap formValidator library, with remote method,
but its not making any proper result.
It always shows the same message, whether its wrong or right, dont know whats wrong.
remote.php
<?php
include("dbcontroller");
$dbhandle=new DBcontroller();
header('Content-type: application/json');
include("connect.php");
$sql="select * from members";
$temp=array();
$result=$db_handle->runQuery($sql);
foreach($result as $row)
{
$temp[]=$row['email'];
}
$valid = true;
if (isset($_POST['email'])) {
$email = $_POST['email'][0];
foreach ($temp as $k => $v) {
if ($email == $v) {
$valid = false;
break;
}
}
}
echo json_encode(array(
'valid' => $valid,
));
?>
Form.php
<div class="form-group">
<label class="col-lg-2 control-label">Email</label>
<div class="col-lg-8">
<input type="text" placeholder="Email" id="e_mail" class="form-control" name="email[]" autocomplete="off"/>
</div>
</div>
Javascript file
'emaill[]': {
validators: {
notEmpty: {
message: 'The email address is required and can\'t be empty'
},
emailAddress: {
message: 'The input is not a valid email address'
},
remote: {
message: 'The email is already exist. you are already a registered user. please try to login?',
url: 'remote.php',
data:{
type:'email'
},
type: 'POST',
delay: 2000
}
}
}
Why don't you do the check in your SQL query?
$sql = "SELECT email FROM members WHERE email = '".$_POST['email']."'";
Now you only have to check if it returns more than 0 results:
$valid = false;
$result=$db_handle->runQuery($sql);
if(sizeOf($results) > 0) {
$valid = true;
}
Although you probably should escape the $_POST the avoid SQL injection ;-)
I am using jQuery Validation plug-in in my two step registration form.
On "First Step" I'm checking username and email availability with remote function.
Here is the bug (or me!):
If username exist in database and email is not, when I click "next" button the script letting me go to second step. (It shouldn't because username exist!)
but;
If username not exist and email is exist in the database, It's stops me there and warns me email is exist. So it's working.
If both username and email exist in the database, also stops me. So again working.
Here is code I'm using;
HTML:
<div class="tab-content">
<p>Page.</p>
<form class="form-horizontal" onsubmit="return false;" action="" method="post" id="myform">
<div id="stepusername">
<p>This is step 1</p>
<input type="text" class="form-control" id="username" name="username" placeholder="Username" autocomplete="off"><br>
<input type="email" class="form-control" id="email" name="email" placeholder="email" autocomplete="off"><br>
<p><a class="btn btn-primary next">Go to step 2</a></p>
</div><!-- signup_one ends -->
<div id="stepemail">
<p>This is step 2</p>
<input type="password" class="form-control" id="password" name="password" placeholder="password" autocomplete="off"><br>
<input type="password" class="form-control" id="conf_password" name="conf_password" placeholder="password" autocomplete="off"><br>
<input class="btn btn-success next" type="submit" value="Finish">
</div><!-- step2 ends -->
</form>
<div id="stepsuccess">
<p>Show result here.</p>
</div><!-- success ends -->
</div><!-- tab-content ends -->
Java Script:
<script type="text/javascript">
// jQuery.validate script, does client-side validation
$(document).ready(function(){
$(".next").click(function(){
var form = $("#myform");
form.validate({
errorElement: 'div',
errorClass: 'formerror',
highlight: function(element, errorClass, validClass) {
$(element).closest('.form-group').addClass("has-error");
},
unhighlight: function(element, errorClass, validClass) {
$(element).closest('.form-group').removeClass("has-error");
},
rules: {
username: {
required: true,
remote: {
url: "check-username.php",
async: false,
type: "post", }
},
password : {
required: true,
},
conf_password : {
required: true,
equalTo: '#password',
},
email: {
required: true,
remote: {
url: "check-email.php",
async: false,
type: "post", }
},
},
messages: {
username: {
required: "Username required",
remote: "Taken username.",
},
password : {
required: "Password required",
},
conf_password : {
required: "Password required",
equalTo: "Password don't match",
},
email: {
required: "Email required",
remote: "Taken email.",
},
}
});
if (form.valid() === true){
if ($('#stepusername').is(":visible")){
current_fs = $('#stepusername');
next_fs = $('#stepemail');
}else if($('#stepemail').is(":visible")){
current_fs = $('#stepemail');
next_fs = $('#stepsuccess');
}
next_fs.show();
current_fs.hide();
}
});
});
</script>
Update:
check-username.php
<?php
error_reporting(E_ERROR | E_PARSE);
try {
$handler = new PDO('mysql:host=localhost;dbname=users', 'root', '');
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo $e->getMessage();
die();
}
$request = $_REQUEST['username'];
$query = $handler->query("SELECT * from usertable WHERE username='$request'");
$results = $query->fetch(PDO::FETCH_ASSOC);
if(empty($request)) {
echo 'false' ;
}else {
if ($results == 0) {
$valid = 'true';
}
else {
$valid = 'false';
}
echo $valid ;
}
?>
check-email.php
<?php
error_reporting(E_ERROR | E_PARSE);
try {
$handler = new PDO('mysql:host=localhost;dbname=users', 'root', '');
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo $e->getMessage();
die();
}
$request = $_REQUEST['email'];
$query = $handler->query("SELECT * from usertable WHERE email='$request'");
$results = $query->fetch(PDO::FETCH_ASSOC);
if(empty($request)) {
echo 'false' ;
}else {
if ($results == 0) {
$valid = 'true';
}
else {
$valid = 'false';
}
echo $valid ;
}
?>
Also jsFiddle if you like to see: http://jsfiddle.net/noptpece/
$query = $handler->query("SELECT * from usertable WHERE username='$request'");
This line doesnt look, if a user exists, whos name equals the content of $request, it looks up if the user with the name "$request" exists, the same with the e-mail.
String composing in PHP works differently, you should write
$query = $handler->query("SELECT * from usertable WHERE username=".$request);
Also you should never ever use a MySQL query like this, because its the easiest thing of the world to inject SQL code and destroy your whole database.
I do have a jquery code to validate my form but unfornutately it is not that accurate. I would like to validate the fields thoroughly like only to accept numbers on phone field and only a valid email address on email field.
Also I would like to show the error ( or just add a red border one field ) as soon as the user types/inputs a value without clicking submit button, so it looks like a real time checker.
Can anyone derive my script, I am really not confident about this. Also derive my php code if u think it is wrong. Would love to learn how to use session also so user can only submit once every session.
Code:
<head>
<script>
$(function () {
$('.cbf').on('submit', function (e) {
e.preventDefault();
var name = $('#name').val();
var phone = $('#phone').val();
var email = $('#email').val();
if ( name == "" ) {
alert('Please provide valid name');
$('#name').addClass('error');
}
else if ( phone == "" ) {
alert('Please provide a valid phone number');
$('#phone').addClass('error');
$('#name').removeClass('error');
}
else if ( email == "" ) {
alert('Please provide a valid email');
$('#email').addClass('error');
$('#phone').removeClass('error');
}
else {
$.ajax({
type: 'post',
url: 'index.php',
data: $('.cbf').serialize(),
data: "name="+ name +"& phone="+ phone +"& email="+ email,
success: function () {
alert('We will contact you shortly! Thanks!');
},
complete:function(){
$('.cbf').each(function(){
this.reset(); //Here form fields will be cleared.
});
}
});
$('#email').removeClass('error');
}
});
});
</script>
</head>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>" class="cbf">
<fieldset>
<input type="text" id="name" name="name" value="" placeholder="Name">
<input type="text" id="phone" name="phone" value="" placeholder="Phone">
<input type="email" id="email" name="email" value="" placeholder="Email Address">
<input type="submit" id="submit" name="submit" value="Get Call Back">
</fieldset>
</form>
<?php
session_start();
if ('POST' === $_SERVER['REQUEST_METHOD']) {
$_SESSION['posted'] = true;
$to = "myemail#gmail.com";
$subject = "Someone wants a Call Back!";
// data the visitor provided
//$name_field = $_POST['name'];
//$phone_field = $_POST['phone'];
//$email_field = $_POST['email'];
$name_field = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email_field = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$phone = filter_var($_POST['phone'], FILTER_SANITIZE_INT);
//constructing the message
$body = " From: $name_field\n\n Phone: $phone_field\n\n E-mail: $email_field\n\n";
// ...and away we go!
mail($to, $subject, $body);
} else {
// handle the error somehow
}
?>
Try this code :
$("#signupform").validate({
rules: {
email: {
required: true,
email: true
},
mobile: {
required: true,
number: true,
minlength: 10,
maxlength: 10
}
},
messages: {
email: {
required: "Please enter a valid email address.",
email: "Invalid Email Address."
},
mobile: {
required: "Please provide a mobile number.",
minlength: "Your mobile number must be 10 characters long.",
maxlength: "Your mobile number must be 10 characters long.",
number: "Please Enter number only."
}
}
});
Its better to validate on both server side and client side. Client side validate then display the error to user. On server side, you need to validate again, just because your JS code can be changed by malicious user.
A simple example with phone.
//client side
var phone = $('#phone').val();
//validate
if(/^\d+$/.test(phone) === false){ //not number
alert('Your phone number is not valid');
}
//on server side
$phone = $_POST['phone'];
if(is_numeric($phone)){
insert $phone into database.
}
Another way is to use HTML5 and new tags like : "email" and "tel" (tel is not supported for the moment) :
<input type="tel" name="phone" required>
and for email :
<input type="email" name="email" required>
Even the solution you choose, you have to do a control on the server side in Php for your case.
It's not the solution but in the futur, I think we should use these tags.
More informations : http://www.w3schools.com/html/html5_form_input_types.asp
Here is a simple jQuery validation:
The form:
<form id="myform">
email<input type="text" name="field1" />
<br/>
password<input type="text" name="field2" />
<br/>
<input type="submit" />
</form>
The validation part
$(document).ready(function () {
$('#myform').validate({ // initialize the plugin
rules: {
field1: {
required: true,
email: true
},
field2: {
required: true,
minlength: 5
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
});
http://jsfiddle.net/VuPPy/