I have a form through which i wish to add values in database. it is working fine, for validation i have added server end validation, but the errors if any get displayed after the form has been submitted, i wish to use user end validation in a way that if a user does not enter a field, is not entering a proper format or the password do not match, the error should get displayed simultaneously i.e before hitting the submit button. Can anyone tell how it can be done
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["email"]))
{
$emailErr = "Email is required";
}
else
{
$email =$_POST["email"];
}
if (empty($_POST["password"]))
{
$pswrdErr = "password is required";
}
else
{
$password = $_POST["password"];
}
if ($_POST["password"]!=$_POST["retype_password"])
{
$pswrdErr = "password does not match";
}
else
{
$password = $_POST["password"];
}
//insert query to add values in database
}
?>
<form name="form" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" >
<input type="text" placeholder="Name" name="name"/>
<input type="email" placeholder="Email" name="email"/>
<input type="password" placeholder="Password" name="password"/>
<input type="password" placeholder="Retype Password" name="retype_password"/>
<button name ="submit" value = "submit" class="btn btn-greensea b-0 br-2 mr-5">Register</button>
</form>
You can try this
<!DOCTYPE html>
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["email"]))
{
$emailErr = "Email is required";
}
else
{
$email =$_POST["email"];
}
if (empty($_POST["password"]))
{
$pswrdErr = "password is required";
}
else
{
$password = $_POST["password"];
}
if ($_POST["password"]!=$_POST["retype_password"])
{
$pswrdErr = "password does not match";
}
else
{
$password = $_POST["password"];
}
//insert query to add values in database
}
?>
<form name="form" id="register-form" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" >
<input type="text" placeholder="Name" name="name"/>
<input type="email" placeholder="Email" name="email"/>
<input type="password" placeholder="Password" name="password" id="password"/>
<input type="password" placeholder="Retype Password" name="retype_password" id="retype_password"/>
<button name ="submit" value = "submit" class="btn btn-greensea b-0 br-2 mr-5">Register</button>
</form>
<script>
(function($,W,D)
{
var JQUERY4U = {};
JQUERY4U.UTIL =
{
setupFormValidation: function()
{
//form validation rules
$("#register-form").validate({
rules: {
name: "required",
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 5,
},
retype_password: {
equalTo :'#password'
}
},
messages: {
name: "Please enter your name",
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long",
},
email: "Please enter a valid email address",
agree: "Please accept our policy"
},
submitHandler: function(form) {
form.submit();
}
});
}
}
//when the dom has loaded setup form validation rules
$(D).ready(function($) {
JQUERY4U.UTIL.setupFormValidation();
});
})(jQuery, window, document);
</script>
</body>
</html>
use jquery code for client side validation
$(form).submit(function(e){
if($("input[name='name']").val()=="")
{
e.preventDefault();//this will stop form from submitting
//show msg name is required
}
});
Related
Please I'm getting uncaught SyntaxError: Unexpected identifier in line 5 email subject: { also the code is not working. What is the problem?
<script>
jQuery(document).ready(function($){
$("#contactform").validate({
rules: {
email subject: {
required: true,
},
email: {
required: true,
email: true
},
message:{
required: true,
}
},
messages: {
email subject: {
required: "Please select a valid email subject.",
},
email: {
required: "Please your valid email address",
email: "Please your valid email address"
},
message: {
required: "Please enter your message",
}
}
});
});
</script>
EDIT 1: I've changed email address to email_address and also in html the problem has gone but the jquery validation is not working ...
Here is my full code:
<?php
require_once 'core/init.php';
include 'includes/head.php';
$hasError = false;
$sent = false;
if (isset($_POST['submitform'])) {
$email = trim($_POST['email']);
$message = trim(htmlspecialchars($_POST['message'], ENT_QUOTES));
$fieldsArray = array(
'email' => $email,
'message' => $message
);
$errorArray = array();
foreach($fieldsArray as $key => $val) {
switch ($key) {
case 'message':
if(empty($val)) {
$hasError = true;
$errorArray[$key] = ucfirst($key) . " field was left empty.";
}
break;
case 'email':
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$hasError = true;
$errorArray[$key] = "Invalid Email Address entered";
}else{
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
}
break;
}
}
if($hasError !== true) {
$to = "example#gmail.com";
$subject = "Message ";
$msgcontents = "Email: $email<br>Message: $message";
$headers = "MIME-Version: 1.0 \r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1 \r\n";
$headers .= "From: $name <$email> \r\n";
$mailsent = mail($to, $subject, $msgcontents, $headers);
if($mailsent) {
$sent = true;
unset($email);
unset($message);
}
}
}
?>
<div class="container-fluid">
<h4 class="text-left" id="backcolor" style="margin-top:205px;">
<a style="text-decoration:none;" href="customerservice.php">Customer Service</a> > Contact us</h4>
<h2>Contact us</h2>
<h4>Contact Us</h4>
<br>
<p>Please visit our Customer Service page, which may provide the answer you are looking for.</p>
<br>
<p>If there are ways that we can better delight you, please contact us by completing the form below.</p>
<div class="row">
<form id="contactform" method="post" novalidate>
<?php
if($sent == true) {
echo "<h2 class='success'>Thanks, your message has been sent</h2>";
} elseif($hasError == true) {
echo '<ul class"errorlist">';
foreach($errorArray as $key => $val){
echo "<li>" . ucfirst($key) . " field error - $val</li>";
}
echo '<ul>';
}
?>
<div class="form-group col-md-6">
<label for="email_subject"><span>* </span>Email Subject</label>
<select class="form-control" id="email_subject" name="email_subject">
<option >Select Email Subject</option>
<option >My Account</option>
<option >Orders</option>
<option >Product Information Questions</option>
<option >Website Technical Questions</option>
<option >Suggestions or Comments</option>
</select>
</div>
</div>
<br>
<div class="row">
<div class="form-group col-md-6">
<label for="message"><span>* </span>Message</label>
<textarea id="message" name="message" value="<?= (isset($message) ? $message : "");?>" class="form-control" rows="10"
style="background-color:#EEEEEE; border:none;"></textarea>
</div>
</div>
<br>
<div class="row">
<div class="form-group col-md-6">
<label for="email"><span>* </span>Your Email Address</label>
<input type="email" name="email" value="<?= (isset($email) ? $email : "");?>" class="form-control"
id="email" style="background-color:#EEEEEE;">
</div>
</div>
<br>
<div class="form-group">
<input type="submit" value="SUBMIT" class="btn btn-success btn-lg" name="submitform">
</div><div class="clearfix"></div>
</form>
</div>
<script>
jQuery(document).ready(function($){
$("#contactform").validate({
rules: {
email_subject: {
required: true,
},
email: {
required: true,
email: true
},
message:{
required: true,
}
},
messages: {
email_subject: {
required: "Please select a valid email subject.",
},
email: {
required: "Please your valid email address",
email: "Please your valid email address"
},
message: {
required: "Please enter your message",
}
}
});
});
</script>
And in the head.php:
<script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.min.js"></script>
Please help !!!
You cannot use spaces in object keys as you did
email subject: {
required: true
}
Instead wrap key in quotes like
"email subject": {
required: true
}
or use a key without spaces.
email_subject: {
required: true
}
Dont give spaces in object keys
Use this-
<script>
jQuery(document).ready(function($){
$("#contactform").validate({
rules: {
email_subject: {
required: true,
},
email: {
required: true,
email: true
},
message:{
required: true,
}
},
messages: {
email_subject: {
required: "Please select a valid email subject.",
},
email: {
required: "Please your valid email address",
email: "Please your valid email address"
},
message: {
required: "Please enter your message",
}
}
})}
});
</script>
There should not be any space for the objectproperty name.
email subject: {
required: true,
},
Replace email subject by email_subject or anything meanigful name without space.
Like the answer above my answer, you might change your email subject instead email_subject cause identifier can't use space on it, and you need change identifier on your input form, like these <input type="email" id="email_subject" name="email_subject">
Here let me help you with your code
<script>
jQuery(document).ready(function($){
$("#contactform").validate({
rules: {
email_subject: {
required: true,
},
email: {
required: true,
email: true
},
message:{
required: true,
}
},
messages: {
email_subject: {
required: "Please select a valid email subject.",
},
email: {
required: "Please your valid email address",
email: "Please your valid email address"
},
message: {
required: "Please enter your message",
}
}
});
});
</script>
And do not forget on your form input, you need changed name and id into email_subject
This is my website: http://bbb.antalyabalikcilik.com.tr/contact-us.html
I have a contact form. I get emails to my email address but the form doesn't show up after email sending 'THANK YOU' alert.
html code:
<!-- contact form -->
<div class='grid_col grid_col_8'>
<div class='ce clearfix'>
<h3 class="ce_title">Drop us a line</h3>
<div>
<div role="form" class="cf" id="cf-f16-p10-o1" lang="en-US" dir="ltr">
<div class="screen-reader-response"></div>
<form action="email.php" method="post" class="cf-form contact-form" novalidate="novalidate">
<p>Name*
<br />
<span class="cf-form-control-wrap your-name"><input type="text" name="name" value="" size="107" class="cf-form-control cf-text cf-validates-as-required" aria-required="true" aria-invalid="false" />
</span>
</p>
<p>Email*
<br />
<span class="cf-form-control-wrap your-email"><input type="email" name="email" value="" size="107" class="cf-form-control cf-text cf-email cf-validates-as-required cf-validates-as-email" aria-required="true" aria-invalid="false" />
</span>
</p>
<p>Message
<br />
<span class="cf-form-control-wrap your-message"><textarea name="message" cols="107" rows="8" class="cf-form-control cf-textarea" aria-invalid="false"></textarea>
</span>
</p>
<p>
<input type="submit" value="Gönder" class="cf-form-control cf-submit" />
</p>
<div class="cws_msg_box error-box clearfix">
<div class="icon_section"><i class="fa fa-exclamation"></i></div>
<div class="content_section">
<div class="msg_box_title">Error box</div>
<div class="msg_box_text"></div>
</div>
</div>
</form>
<div class="email_server_responce"></div>
</div>
</div>`enter code here`
</div>
</div>
<!-- / conatct form -->
email.php
<?php
$name = $_REQUEST['name'] ;
$email = $_REQUEST['email'] ;
$message = $_REQUEST['message'] ;
require("class.phpmailer.php");
$mail = new PHPMailer();
$mail->IsSMTP(); // set mailer to use SMTP
$mail->Host = "mail.xxx.com."; // specify main and backup server
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "xxx#xxx.com"; // SMTP username
$mail->Password = "123456789"; // SMTP password
$mail->From = "xxx#xxx.com";
$mail->FromName = "www.xxx.com";
$mail->AddAddress("xxx#hotmail.com");
$mail->WordWrap = 50; // set word wrap to 50 characters
$mail->IsHTML(true); // set email format to HTML
$mail->Subject = "received from website email";
$mail->Body = $message;
$mail->AltBody = $message;
$content = '<div style="background: #eee; padding: 10px; font-size: 14px; font-family: comic sans ms">
İsim : '.$name.'<br />
Email : '.$email.'<br />
Mesaj : '.$message.'</div>';
$mail->MsgHTML($content);
if(!$mail->Send())
{
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "Message has been sent";
?>
js code:
/* contact form */
if (jQuery(".contact-form").length) {
/**/
/* contact form */
/**/
/* validate the contact form fields */
jQuery(".contact-form").each(function(){
jQuery(this).validate( /*feedback-form*/{
onkeyup: false,
onfocusout: false,
errorElement: 'p',
errorLabelContainer: jQuery(this).find('.msg_box_text'),
rules:
{
name:
{
required: true
},
email:
{
required: true,
email: true
},
message:
{
required: true
},
verify: {
required: true,
remote: {
url: 'php/check-capcha.php',
type: "post",
data:
{
code: function()
{
return jQuery('.verify').val();
}
}
}
}
},
messages:
{
name:
{
required: 'Please enter your name',
},
email:
{
required: 'Please enter your email address',
email: 'Please enter a VALID email address'
},
message:
{
required: 'Please enter your message'
},
verify: {
required: 'Please enter Captcha',
remote: "Please enter a VALID Captcha"
}
},
invalidHandler: function()
{
jQuery(this).find(".cws_msg_box.error-box").slideDown('fast');
jQuery("#feedback-form-success").slideUp('fast');
},
submitHandler: function(form)
{
jQuery(form).find(".cws_msg_box.error-box").slideUp('fast');
var $form = jQuery(form).ajaxSubmit();
submit_handler($form, jQuery(form).parent().children(".email_server_responce") );
}
});
})
/* Ajax, Server response */
var submit_handler = function (form, wrapper){
var $wrapper = jQuery(wrapper); //this class should be set in HTML code
$wrapper.css("display","block");
var data = {
action: "email_server_responce",
values: jQuery(form).serialize()
};
//send data to server
jQuery.post("email.php", data, function(s_response) {
s_response = jQuery.parseJSON(s_response);
if(s_response.info == 'success'){
$wrapper.addClass("message message-success").append('<div class="cws_msg_box success-box clearfix"><div class="icon_section"><i class="fa fa-thumbs-up"></i></div><div class="content_section"><div class="msg_box_title">Success!</div><div class="msg_box_text">Your message was successfully delivered.</div></div></div>');
$wrapper.delay(5000).hide(500, function(){
jQuery(this).removeClass("message message-success").text("").fadeIn(500);
$wrapper.css("display","none");
});
jQuery(form)[0].reset();
} else {
$wrapper.addClass("cws_msg_box error-box clearfix").append("<div class='icon_section'><i class='fa fa-exclamation'></i></div><div class='content_section'><div class='msg_box_title'>Server fail!</div><div class='msg_box_text'><p> Please try again later!</p></div></div>");
$wrapper.delay(5000).hide(500, function(){
jQuery(this).removeClass("cws_msg_box error-box clearfix").text("").fadeIn(500);
$wrapper.css("display","none");
});
}
});
return false;
}
}
/**/
What is wrong?Please help me...
I have searched but I get info about how to disable submit button till all fields are completed....
I have following form where some fields are required and some are optional.
I want to disable submit button till required fields are completed.
sample code of form :
<form name="registration_form" id="registration_form" action="nextaction.php" method="post" enctype="multipart/form-data" >
Name : <input type="text" id="name" name="name" required>
Email : <input type="text" id="name" name="name" required>
Mobile : <input type="text" id="mobile" name="mobile" required>
Gender : <input type="text" id="gender" name="gender" >/*optional*/
Occupation : <input type="text" id="occupation" name="occupation" >/*optional*/
City : <input type="text" id="city" name="city" required>
Avatar : <input type="file" id="avatar" name="avatar" required>
<input type="submit" class="link-button-blue" id="register" value="PROCEED TO NEXT STEP" />
===========
Edited
what I have tried for submit disable untill all field completed as follows :
First Thing :
<input type="submit" class="link-button-blue" id="register" value="PROCEED TO NEXT STEP" disabled="disabled" />
script :
<script>
$(document).ready(function (){
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#register').attr('disabled', 'disabled');
} else {
$('#register').removeAttr('disabled');
}
});
});
</script>
$('#registration_form input[required]').on('input propertychange paste change', function() {
var empty = $('#registration_form').find('input[required]').filter(function() {
return this.value == '';
});
$('#register').prop('disabled', (empty.length));
});
https://jsfiddle.net/ot5kn5c7/
This should work.
Anytime anything changes on any required input check for the count of required fields that are not empty. Once there are 0 required empty inputs update the disabled property for the button. (0 evaluates as false)
If you didn't to disable the button and wanted to only stop the form from submitting you would attach to the submit event on the form and just prevent the default action using similar logic checking the length.
$('form').on('submit', function(e) {
var empty = $(this).find('input[required]').filter(function() {
return this.value == '';
});
if (empty.length) {
e.preventDefault();
alert('enter all required field!')
}
});
Working solution for your case: https://jsfiddle.net/j9r5ejho/
$('form').submit(function(){
var valid = true;
$('input[required]').each(function(i, el){
if(valid && $(el).val()=='' ) valid = false;
})
return valid;
})
Untested but it should work with something like this:
(function() {
// whenever you type in a field
$('form > input').keyup(function() {
var empty = false;
// scan all fields in this form with the attribute required
$('form').find('input[required]').each(function() {
// if it's empty, cancel the loop
if ($(this).val() == '') {
empty = true;
return false;
}
});
// in case we have an empty required field,
// disable submit button
if (empty) {
$('input:submit').attr('disabled', 'disabled');
} else {
$('#register').removeAttr('disabled');
}
});
})();
In order to prevent posting the form on a button or input type="submit", you can simply use e.preventDefault() which would prevent from proceeding with the default behavior.If you are using jquery validation and have a required attribute, you can just invoke $.validate() to validate the form.
$('input:submit').click(function(e)
{
if(!$.validate())
e.preventDefault();
});
example : https://jsfiddle.net/DinoMyte/suj951ga/1/
Just in case you want to try something like this. This won't disable the submit button but if you want to stop it from submitting until all required fields are fill in. This should work.
Not sure what database your using but this is for the PDO. You can just change the connection part to mysqli.
It won't submit to your database until you complete all the required fields and will also display the required input error messages.
It won't clear all the fields if you forget to fill in one of the required fields and submit.
<?php
// define variables and set to empty values
$nameErr = $emailErr = $cityErr = $commentErr = $genderErr = "";
$name = $email = $city = $comment = $gender = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Please add a name";
} else {
$name = validateInput($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]+/",$name)) {$nameErr = "Only letters and white
space allowed";}
}
if (empty($_POST["email"])) {
$emailErr = "Please add an email";
} else {
$email = validateInput($_POST["email"]);
// check if email is an email format
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
$emailErr = "Invalid email format";
}
}
if (empty($_POST["city"])) {
$cityErr = "Please add your city";
} else {
$city = validateInput($_POST["city"]);
// check if city only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$city)) {
$cityErr = "Only letters and white space allowed";
}
}
if (empty($_POST["comment"])) {
$commentErr = "Please add your comment";
} else {
$comment = validateInput($_POST["comment"]);
// check if comment only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$comment)) {
$commentErr = 'Only "/", "-", "+", and numbers';
}
}
if (empty($_POST["gender"])) {
$genderErr = "Please pick your gender";
} else {
$gender = validateInput($_POST["gender"]);
}
}
// Validate Form Data
function validateInput($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if(!empty($_POST["name"]) && !empty($_POST["email"]) && !empty($_POST["city"]) && !empty($_POST["comment"]) && !empty($_POST["gender"]))
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO info (name, email, city, comment, gender)
VALUES ('$name', '$email', '$city', '$comment', '$gender')";
// use exec() because no results are returned
$conn->exec($sql);
echo "Success! Form Submitted!";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
?>
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<h2>PHP Form</h2>
<p>Doesn't submit until the required fields you want are filled</p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="error">
<p><span>* required field</span></p>
<div><?php echo $nameErr;?></div>
<div><?php echo $emailErr;?></div>
<div><?php echo $cityErr;?></div>
<div><?php echo $commentErr;?></div>
<div><?php echo $genderErr;?></div>
</div>
<label for="name">Name:
<input type="text" name="name" id="name" placeholder="" value="<?php echo $name;?>">
<span class="error">*</span>
</label>
<label for="email">Email:
<input type="email" name="email" id="email" placeholder="" value="<?php echo $email;?>">
<span class="error">*</span>
</label>
<label for="city">city:
<input type="text" name="city" id="city" placeholder="" value="<?php echo $city;?>">
<span class="error">*</span>
</label>
<label for="comment">comment:
<input type="text" name="comment" id="comment" value="<?php echo $comment;?>">
<span class="error">*</span>
</label>
<label for="gender">Gender:<br>
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="other") echo "checked";?> value="other">Other
<span class="error">*</span>
</label>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
Use this if you want to redirect it to another page so it won't send the form again to your PDO database if they refresh it.
It won't submit to your database and will stay on the HOME.PHP page until you complete all the required fields and will also display the required input error messages while on HOME.PHP page.
It won't clear all the fields if you forget to fill in one of the required fields and submit.
Added a "header("Location: welcome.php");" after "$conn->exec($sql);"
HOME.PHP
<?php
// define variables and set to empty values
$nameErr = $emailErr = $cityErr = $commentErr = $genderErr = "";
$name = $email = $city = $comment = $gender = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Please add a name";
} else {
$name = validateInput($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]+/",$name)) {$nameErr = "Only letters and white space allowed";}
}
if (empty($_POST["email"])) {
$emailErr = "Please add an email";
} else {
$email = validateInput($_POST["email"]);
// check if email is an email format
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
$emailErr = "Invalid email format";
}
}
if (empty($_POST["city"])) {
$cityErr = "Please add your city";
} else {
$city = validateInput($_POST["city"]);
// check if city only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$city)) {
$cityErr = "Only letters and white space allowed";
}
}
if (empty($_POST["comment"])) {
$commentErr = "Please add your comment";
} else {
$comment = validateInput($_POST["comment"]);
// check if comment only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$comment)) {
$commentErr = 'Only "/", "-", "+", and numbers';
}
}
if (empty($_POST["gender"])) {
$genderErr = "Please pick your gender";
} else {
$gender = validateInput($_POST["gender"]);
}
}
// Validate Form Data
function validateInput($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if(!empty($_POST["name"]) && !empty($_POST["email"]) && !empty($_POST["city"]) && !empty($_POST["comment"]) && !empty($_POST["gender"]))
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO info (name, email, city, comment, gender)
VALUES ('$name', '$email', '$city', '$comment', '$gender')";
// use exec() because no results are returned
$conn->exec($sql);
header("Location: welcome.php");
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
?>
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<h2>PHP Form</h2>
<p>Doesn't submit until the required fields you want are filled</p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="error">
<p><span>* required field</span></p>
<div><?php echo $nameErr;?></div>
<div><?php echo $emailErr;?></div>
<div><?php echo $cityErr;?></div>
<div><?php echo $commentErr;?></div>
<div><?php echo $genderErr;?></div>
</div>
<label for="name">Name:
<input type="text" name="name" id="name" placeholder="" value="<?php echo $name;?>">
<span class="error">*</span>
</label>
<label for="email">Email:
<input type="email" name="email" id="email" placeholder="" value="<?php echo $email;?>">
<span class="error">*</span>
</label>
<label for="city">city:
<input type="text" name="city" id="city" placeholder="" value="<?php echo $city;?>">
<span class="error">*</span>
</label>
<label for="comment">comment:
<input type="text" name="comment" id="comment" value="<?php echo $comment;?>">
<span class="error">*</span>
</label>
<label for="gender">Gender:<br>
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="other") echo "checked";?> value="other">Other
<span class="error">*</span>
</label>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
WELCOME.PHP
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=\, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>Success! Form Submitted!</h1>
<script type="text/javascript" src="js/main.js" ></script>
</body>
</html>
I have a sign up form that uses AJAX to pass the data to a PHP script and enter it into a MySQL database.
However, the issue I am having is that when someone enters a username like so this:
"Username Test" the space isn't parsed properly, so when you go to view the profile of that user via a link it won't work.
So my question is how to parse a space within Javascript and PHP if you know as well but I'm pretty sure the PHP side of things is good.
Firebug outputs this when the form is submitted:
Parameters application/x-www-form-urlencoded
emailSignUp nickdimartino91#gmail.com
passwordSignUp nidima10
usernameSignUp Username Test
Source
usernameSignUp=Username+Test&passwordSignUp=nidima10&emailSignUp=nickdimartino91%40gmail.com
I echo'd the value of the username field within the PHP script and it returns with a space in the username. Yet it's not getting entered that way into the DB. What is the issue?
UPDATE: Not sure what I did but all is working now!
Sign up form:
<form action="<?php echo $_SERVER['PHP_SELF'];?>" id="signUpForm" method="post" name="signUpForm">
<input class="formInput" id="usernameSignUp" name="usernameSignUp" placeholder="Username" required="required" type="text" style="margin-right: 6px;">
<input class="formInput" id="passwordSignUp" name="passwordSignUp" placeholder="Password" required="required" type="password" /><br>
<input class="formInput" id="emailSignUp" name="emailSignUp" placeholder="Email" required="required" type="email" style="margin-bottom: 10px; margin-top: 10px; width: 326px;"><br>
<input class="formButton" id="signUpSubmit" name="signUpSubmit" type="submit" value="Sign Up">
<div id="signUpLoading" style="display: none; height: auto; margin-top: 10px; width: auto;"><img alt="Loading" src="/images/loading.gif"><span class="loadingMessage">Signing up...</span></div>
<div id="signUpResponse" style="display: none; height: auto; margin-top: 10px; width: auto;"></div>
</form>
JS bit that does the AJAX stuff:
<script>
$(document).ready(function() {
$("#signUpForm").submit(function() {
$(document).ajaxStart(function() {
$("#signUpLoading" ).show();
});
$.ajax({
url:"/ajax/signUp.php", // Action of the form
data:$("#signUpForm").serialize(), // Send forms data to server
dataType:"JSON", // Take response as JSON
type:"POST", // Send form by post or get
complete:function(result) {
$(document).ajaxStop(function() {
$("#signUpLoading" ).hide();
});
$("#signUpResponse").html(result.responseText);
$("#signUpResponse").slideDown("slow");
}
});
return false; // Default submit return false
});
});
</script>
signUp.php
<?php
require('../core/core.php');
if (!empty($_POST)) {
$username = $_POST['usernameSignUp'];
$password = $_POST['passwordSignUp'];
$email = strtolower($_POST['emailSignUp']);
if (empty($username)) {
$errors[] = '<img alt="Error" src="/images/error.png"><span class="errorMessage">Please enter a username.</span>';
}
elseif (empty($password)) {
$errors[] = '<img alt="Error" src="/images/error.png"><span class="errorMessage">Please enter a password.</span>';
}
elseif (empty($email)) {
$errors[] = '<img alt="Error" src="/images/error.png"><span class="errorMessage">Please enter your email address.</span>';
}
elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = '<img alt="Error" src="/images/error.png"><span class="errorMessage">Please enter a valid email address.</span>';
}
elseif (strlen($username) < 2 || strlen($username) > 32) {
$errors[] = '<img alt="Error" src="/images/error.png"><span class="errorMessage">Your username must be between 2 and 32 characters long.</span>';
}
elseif (strlen($password) < 6 || strlen($password) > 32) {
$errors[] = '<img alt="Error" src="/images/error.png"><span class="errorMessage">Your password must be between 6 and 32 characters long.</span>';
}
elseif ($users->userExists($username) === true) {
$errors[] = '<img alt="Error" src="/images/error.png"><span class="errorMessage">The username you\'ve entered is unavailable.</span>';
}
elseif ($users->emailExists($email) === true) {
$errors[] = '<img alt="Error" src="/images/error.png"><span class="errorMessage">The email you\'ve entered is already associated with another account.</span>';
}
else {
$hashedPassword = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);
$users->signUp($username, $hashedPassword, $email);
echo '<img alt="Success" src="/images/success.png"><span class="successMessage">Thanks for joining the LiveGrooves Community!<br>We\'ve sent you an email with your account information, an activation link, and some tips on getting started.</span>';
return true;
}
}
if (!empty($errors)) {
echo '<p>' . implode('</p><p>', $errors) . '</p>';
}
?>
Hello I am wondering if this is possible? Having two different forms on the same page using the jquery post to send it php to do some checking. The first from works flawlessly, however when I go to the second form I get an error saying it is an undefined variable but I am using the exact same method I used for the first form. It will load anything echoed in the php page for the feed form but will not echo back what I am typing in. Is there a better, more correct way to do it?
This is not for a real site, just testing for a project I am working on.
HTML:
<form action="php/signup.php" method="post" class="form-inline" name="signupForm">
<input type="text" maxlength="20" name="username" id="user_in">
<input type="password" maxtlength="20" name="password" id="pass_in">
<input type="submit" name="submit" Value="Sign Up">
</form>
<div id="feedback"></div> <!-- Feedback for Sign Up Form -->
<br /><br />
<form name="feedForm">
<input type="text" id="feed_in" name="feed_me_in" placeholder="feed">
<div id="feedme"></div> <!-- FEEDback for feed form -->
</form>
<script src="js/jquery-1.9.1.js"></script>
JavaScript:
<script>
$(document).ready(function() {
$('#feedback').load('php/signup.php').show();
//SIGN IN FORM
$('#user_in, #pass_in').keyup(function() {
$.post('php/signup.php', { username: document.signupForm.username.value,
password: document.signupForm.password.value },
function(result) {
$('#feedback').html(result).show
});
});
$('#feedme').load('php/feed.php').show();
//FEED FORM
$('#feed_in').keyup(function() {
$.post('php/feed.php', { feed: document.feedForm.feed_me_in.value },
function(result) {
$('$feedme').html(result).show
});
});
});
</script>
PHP for Feed Form:
<?php
$feed = mysql_real_escape_string($_POST['feed']);
if(isset($feed)) {
echo $feed;
} else {}
?>
PHP for the Sign Up Form:
<?php
if(isset($_POST['username'])) {
include_once('connect.php'); //Connect
$username = mysql_real_escape_string($_POST['username']);
$sql1 = "SELECT username FROM users WHERE username='$username'";
$check = mysql_query($sql1);
$numrows = mysql_num_rows($check);
if(strlen($username)<=4) {
echo "Username is too short";
} elseif($numrows == 0) {
echo "Username is available";
} elseif($numrows > 0) {
echo "Username is already taken";
}
} else {
echo "Please type a username";
}
?>
$('$feedme').html(result).show
should be
$('#feedme').html(result).show();