Form validation making field required - forms

I'm a newbie here, I'm working on a registration form and trying to figure out why I can't make the "Name" field be required. Email and everything else seems to work fine. What am I missing?
Thx
this is what I have for the signup.js
$(document).ready(function() {
$("#signup-form").submit(function(e){
e.preventDefault();
var $form = $(this),
name = $form.find('input[name="name"]').val(),
email = $form.find('input[name="email"]').val(),
url = $form.attr('action');
$.post(url, {name:name, email:email},
function(data) {
if(data)
{
if(data=="Some fields are missing.")
{
$("#status").text("Please fill in your name and email.");
$("#status").css("color", "red");
}
else if(data=="Invalid name.")
{
$("#status").text("Please fill in your name.");
$("#status").css("color", "red");
}
else if(data=="Invalid email address.")
{
$("#status").text("Please check your email address.");
$("#status").css("color", "red");
}
else if(data=="Invalid list ID.")
{
$("#status").text("Your list ID is invalid.");
$("#status").css("color", "red");
}
else if(data=="Already subscribed.")
{
$("#status").text("You're already subscribed!");
$("#status").css("color", "red");
}
else
{
$("#status").text("You're subscribed! Please check your email for confirmation.");
$("#status").css("color", "green");
}
}
else
{
alert("Sorry, unable to subscribe. Please try again later!");
}
}
);
});
});
html file has this:
<form action="signup.php" method="POST" accept-charset="utf-8" name="signup-form" id="signup-form" class="sign_form" >
<label for="Silver">Get Notified</label>
<div>
<input type="text" name="name" value="" placeholder="Full Name" class="name" />
<input type="text" name="email" value="" placeholder="Email" class="email" />
<input type="submit" value="➜" id="submit-btn" class="submit" />
</div>
<label id="status"></label>
</form>
and the signup.php file is:
<?php
$submit_url = 'http://www.domain.com/signup';
$list = 'list010101';
//POST variables
$name = $_POST['name'];
$email = $_POST['email'];
//subscribe
$postdata = http_build_query(
array(
'name' => $name,
'email' => $email,
'list' => $list,
'boolean' => 'true'
)
);
$opts = array('http' => array('method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata));
$context = stream_context_create($opts);
$result = file_get_contents($submit_url.'/subscribe', false, $context);
echo $result;
?>

I think you should validate before you post because it seems you are posting to the server then checking the values. It's a good idea to validate before you send data to the server.
Something like:
$("#signup-form").submit(function(e){
e.preventDefault();
//use ids to find the form field e.g. <input type='text' id='name'>
var name = $("#name").val();
var email = $("#email").val();
//this is just checking if its an empty string, add your own validation here
if (email == "") return false;
if (name == "") return false;
//return true if validation passes for the form to submit or do your ajax post here
return true;
You could also use this plugin jquery validation

Related

How to add a 'Send Message To' button on contact page?

I'm trying to add a "Send Message To" button on a contact form but I'm having trouble with the javascript/PHP. I'm using code I edited that came with the start bootstrap modern business theme, so far I have just added the $to = '$department', set the select tag ID as department and the value of option tags to the appropriate emails.
Not sure if any of that is correct.
HTML:
<div class="row">
<div class="col-lg-8 mb-4">
<h3>Send us a Message</h3>
<form name="sentMessage" id="contactForm" novalidate>
<div class="control-group form-group">
<div class="controls">
<label>Full Name</label>
<input type="text" class="form-control" id="name" required data-validation-required-message="Please enter your name.">
<p class="help-block"></p>
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<label>Email Address</label>
<input type="email" class="form-control" id="email" required data-validation-required-message="Please enter your email address.">
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<label>Message</label>
<textarea rows="10" cols="100" class="form-control" id="message" required data-validation-required-message="Please enter your message" maxlength="999" style="resize:none"></textarea>
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<label>Send Message To</label>
<select class="form-control" id="department">
<option value="sales#website.com">Sales</option>
<option value="support#website.com">Support</option>
</select>
<p class="help-block"></p>
</div>
</div>
<div id="success"></div>
<!-- For success/fail messages -->
<button type="submit" class="btn btn-CMD" id="sendMessageButton">Send Message</button>
</form>
</div>
</div>
PHP:
<?php
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$message = strip_tags(htmlspecialchars($_POST['message']));
$message = strip_tags(htmlspecialchars($_POST['department']));
// Create the email and send the message
$to = '$department';
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nMessage:\n$message";
$headers = "From: noreply#website.com\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>
Javascript
$(function() {
$("#contactForm input,#contactForm textarea").jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
// additional error messages or events
},
submitSuccess: function($form, event) {
event.preventDefault(); // prevent default submit behaviour
// get values from FORM
var name = $("input#name").val();
var email = $("input#email").val();
var message = $("textarea#message").val();
var firstName = name; // For Success/Failure Message
// Check for white space in name for Success/Fail message
if (firstName.indexOf(' ') >= 0) {
firstName = name.split(' ').slice(0, -1).join(' ');
}
$this = $("#sendMessageButton");
$this.prop("disabled", true); // Disable submit button until AJAX call is complete to prevent duplicate messages
$.ajax({
url: "././mail/contact_me.php",
type: "POST",
data: {
name: name,
email: email,
message: message
},
cache: false,
success: function() {
// Success message
$('#success').html("<div class='alert alert-success'>");
$('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-success')
.append("<strong>Your message has been sent. </strong>");
$('#success > .alert-success')
.append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
error: function() {
// Fail message
$('#success').html("<div class='alert alert-danger'>");
$('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-danger').append($("<strong>").text("Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!"));
$('#success > .alert-danger').append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
complete: function() {
setTimeout(function() {
$this.prop("disabled", false); // Re-enable submit button when AJAX call is complete
}, 1000);
}
});
},
filter: function() {
return $(this).is(":visible");
},
});
$("a[data-toggle=\"tab\"]").click(function(e) {
e.preventDefault();
$(this).tab("show");
});
});
/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
$('#success').html('');
});
Im not quite sure about your questions, but if you're just trying to get the item from the department form, and send it to that email address, this is the code for that.
JS:
data: {
name: name,
email: email,
message: message,
department: document.getElementById('department').value
},
You must pass the value of the form to the PHP script. You originally had the $message var set to the message and then the next line would set that variable to the department. You need to keep them separate.
$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$message = strip_tags(htmlspecialchars($_POST['message']));
$department = strip_tags(htmlspecialchars($_POST['department']));
// Create the email and send the message
$to = $department;
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nMessage:\n$message";
$headers = "From: noreply#website.com\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>
Hope this works!

PHPMailer and Ionic with Gmail

I'm attempting to create a contact form for my app using PHPMailer and Ionic with Gmail.
The page receives (Failed.) result message when it triggers the script but I never get the email from the form. Here is my code:
template.html
<label class="item item-input" ng-class="{ 'has-error': contactform.inputEmail.$invalid && submitted }">
<input ng-model="formData.inputEmail" type="email" class="form-control" id="inputEmail" name="inputEmail" placeholder="Your Email" required>
</label>
<label class="item item-input" ng-class="{ 'has-error': contactform.inputSubject.$invalid && submitted }">
<input ng-model="formData.inputSubject" type="text" class="form-control" id="inputSubject" name="inputSubject" placeholder="Subject Message" required>
</label>
<label class="item item-input" ng-class="{ 'has-error': contactform.inputMessage.$invalid && submitted }">
<textarea ng-model="formData.inputMessage" class="form-control" rows="4" id="inputMessage" name="inputMessage" placeholder="Your message..." required></textarea>
</label>
<div class="padding">
<button type="submit" class="btn btn-default" ng-disabled="submitButtonDisabled">Send Message</button>
</div>
</form>
<p ng-class="result" style="padding: 15px; margin: 0;">{{ resultMessage }}</p>
app.js
.controller('ContactCtrl', function ($scope, $http) {
$scope.result = 'hidden'
$scope.resultMessage;
$scope.formData; //formData is an object holding the name, email, subject, and message
$scope.submitButtonDisabled = false;
$scope.submitted = false; //used so that form errors are shown only after the form has been submitted
$scope.submit = function(contactform) {
$scope.submitted = true;
$scope.submitButtonDisabled = true;
if (contactform.$valid) {
$http({
method : 'POST',
url : 'contact-form.php',
data : $.param($scope.formData), //param method from jQuery
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } //set the headers so angular passing info as form data (not request payload)
}).success(function(data){
console.log(data);
if (data.success) { //success comes from the return json object
$scope.submitButtonDisabled = true;
$scope.resultMessage = data.message;
$scope.result='bg-success';
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = data.message;
$scope.result='bg-danger';
}
});
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = 'Failed.';
$scope.result='bg-danger';
}
}
});
PHP
<?php
require_once 'phpmailer/PHPMailerAutoload.php';
if (isset($_POST['inputName']) && isset($_POST['inputEmail']) && isset($_POST['inputSubject']) && isset($_POST['inputMessage'])) {
//check if any of the inputs are empty
if (empty($_POST['inputName']) || empty($_POST['inputEmail']) || empty($_POST['inputSubject']) || empty($_POST['inputMessage'])) {
$data = array('success' => false, 'message' => 'Please fill out the form completely.');
echo json_encode($data);
exit;
}
//create an instance of PHPMailer
$mail = new PHPMailer();
$mail->From = $_POST['inputEmail'];
$mail->FromName = $_POST['inputName'];
$mail->AddAddress('my#emailaddress.com'); //recipient
$mail->Subject = $_POST['inputSubject'];
$mail->Body = "Name: " . $_POST['inputName'] . "\r\n\r\nMessage: " . stripslashes($_POST['inputMessage']);
$mail->isSMTP();
$mail->Host = gethostbyname('smtp.gmail.com');
$mail->Port = 587;
$mail->SMTPSecure = "tls";
$mail->SMTPAuth = true;
$mail->Username = "mygmailusername#gmail.com";
$mail->Password = "passwordform";
$mail->setFrom('mygmailusername#gmail.com', 'Contact Form');
if (isset($_POST['ref'])) {
$mail->Body .= "\r\n\r\nRef: " . $_POST['ref'];
}
if(!$mail->send()) {
$data = array('success' => false, 'message' => 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo);
echo json_encode($data);
exit;
}
$data = array('success' => true, 'message' => 'Thanks! We have received your message.');
echo json_encode($data);
} else {
$data = array('success' => false, 'message' => 'Please fill out the form completely.');
echo json_encode($data);
}
You need to initialize $scope.formData = {} so that it can hold the values you are expecting. Right now, its trying to bind values to a scope variable that is undefined.
Edit - It looks like you have no ng-click handler in your button to register the click to the submit. Please add this to your button. Additionally, $valid only works if your input values are enclosed in a .
template.html
<form name="myForm">
<label class="item item-input" ng-class="{ 'has-error': contactform.inputEmail.$invalid && submitted }">
<input ng-model="formData.inputEmail" type="email" class="form-control" id="inputEmail" name="inputEmail" placeholder="Your Email" required>
</label>
<label class="item item-input" ng-class="{ 'has-error': contactform.inputSubject.$invalid && submitted }">
<input ng-model="formData.inputSubject" type="text" class="form-control" id="inputSubject" name="inputSubject" placeholder="Subject Message" required>
</label>
<label class="item item-input" ng-class="{ 'has-error': contactform.inputMessage.$invalid && submitted }">
<textarea ng-model="formData.inputMessage" class="form-control" rows="4" id="inputMessage" name="inputMessage" placeholder="Your message..." required></textarea>
</label>
<div class="padding">
<button type="submit" class="btn btn-default"
ng-disabled="myForm.$invalid || submitButtonDisabled == true"
ng-click=submit(formData)>Send Message</button>
</div>
</form>
<p ng-class="result" style="padding: 15px; margin: 0;">{{ resultMessage }}</p>
What this is doing is its registering the $scope.submit the button, and in the HTML you're passing in formData as a parameter. The now has a name and its required values are checked in ng-disabled of the button which refers to the same name and disables if the I've cleaned up your app.js so that you're getting the params correctly.
.controller('ContactCtrl', function ($scope, $http) {
$scope.result = 'hidden'
$scope.resultMessage = '';
$scope.formData; //formData is an object holding the name, email, subject, and message
$scope.submitButtonDisabled = false;
$scope.submitted = false; //used so that form errors are shown only after the form has been submitted
$scope.submit = function(contactform) {
$scope.submitted = true;
$scope.submitButtonDisabled = true;
$http({
method : 'POST',
url : 'contact-form.php',
data : $.param(contactform), //param method from jQuery
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } //set the headers so angular passing info as form data (not request payload)
}).success(function(data){
console.log(data);
if (data.success) { //success comes from the return json object
$scope.submitButtonDisabled = true;
$scope.resultMessage = data.message;
$scope.result='bg-success';
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = data.message;
$scope.result='bg-danger';
}
});
}
});

How to add an attachment to my form

I need to recive audio and images on my form !
I only know how to add in the html(i think i know *?) but have no idea how to add it to jquery or php ...
PS : Extra ... i wanna know how php send and attachment to the e-mail... the attachment is stored in my site ? or it goes directly to the e-mail ?
thanks in advance !
HTML :
<form id="contact1" method="post" >
<fieldset>
Name :
<input name="name" type="text" id="name">
E-mail :
<input name="email" type="text" class="email">
Mensagem :
<textarea name="message" cols="45" rows="8" id="message"></textarea>
Send a file:
<input name="arquivo" type="file"> ??????????????
</fieldset>
<input type="submit" name="enviar" value="Enviar" /></font><br>
</form>
JS :
$("#contact1").submit(function(e){
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
var text = $("#message").val();
var dataString = 'name=' + name + '&email=' + email + '&text=' + text;
if (name.length > 3){
$.ajax({
type: "POST",
url: "/scripts/mailform1.php",
data: dataString,
success: function(){
$('#form1ok').fadeIn(300);
}
});
} else{
$('#form1error').slideDown(200);
}
return false;
});
PHP :
<?php
if ( isset($_POST['email']) && isset($_POST['name']) && isset($_POST['text'])) {
$test = "/(content-type|bcc:|cc:|to:)/i";
foreach ( $_POST as $key => $val ) {
if ( preg_match( $test, $val ) ) {
exit;
}
}
mail( "contact#x.com", "Partner Form: ".$_POST['name'], $_POST['text'], "From:" . $_POST['email'] );
}
?>

CodeIgniter incorrect URL when submitting form

I just started using CodeIgniter today, and was following the tutorial at the CI website.
When I got to the final step for creating a new news item, I ran into an issue with the form submit. I would expect the URL to be jonhopkins.net/news/create when I press the form's submit button, but it is going to http://jonhopkins.net/news/jonhopkins.net/news/create instead, which is clearly very wrong, and I have no idea why this is happening. Does anyone know how to fix this?
Everything else on my site (the Pages part of the tutorial) works perfectly. This is the only thing that is breaking. All of my code is exactly as it appears in the tutorial, except for a change to what happens when an item is successfully submitted to the database, which currently is never happening.
News Controller
public function create() {
$this->load->helper('form');
$this->load->library('form_validation');
$data['title'] = 'Create a news item';
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('text', 'text', 'required');
if ($this->form_validation->run() === FALSE) {
$this->load->view('templates/header', $data);
$this->load->view('news/create');
$this->load->view('templates/footer');
} else {
//$success will contain the slug of the created item, or FALSE if database insertion failed
$success = $this->news_model->set_news();
if ($success) {
$this->_doView($success);
} else {
echo "Something went wrong while trying to submit the news item.";
}
}
}
public function view($slug) {
$this->_doView($slug);
}
private function _doView($slug) {
$data['news_item'] = $this->news_model->get_news($slug);
if (empty($data['news_item'])) {
show_404();
}
$data['title'] = $data['news_item']['title'];
$this->load->view('templates/header', $data);
$this->load->view('news/view', $data);
$this->load->view('templates/footer');
}
Create View
<h2>Create a news item</h2>
<?php echo validation_errors(); ?>
<?php echo form_open('news/create') ?>
<label for="title">Title</label>
<input type="input" name="title" /><br />
<label for="text">Text</label>
<textarea name="text"></textarea><br />
<input type="submit" name="submit" value="Create news item" />
</form>
And the resulting HTML...
<form action="jonhopkins.net/news/create" method="post" accept-charset="utf-8">
<label for="title">Title</label>
<input type="input" name="title" /><br />
<label for="text">Text</label>
<textarea name="text"></textarea><br />
<input type="submit" name="submit" value="Create news item" />
</form>
News Model I don't think it's ever getting here, but just in case
public function set_news() {
$this->load->helper('url');
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
'text' => $this->input->post('text'),
'date' => date("Y-m-d H:i:s")
);
if ($this->db->insert('news', $data)) {
return $slug;
} else {
return FALSE;
}
}
Routes
$route['news/create'] = 'news/create';
$route['news/(:any)'] = 'news/view/$1';
$route['news'] = 'news';
$route['(:any)'] = 'pages/view/$1';
$route['default_controller'] = 'pages/view';
The form_open('news/create') method uses the $CI->Config->site_url() method which, in turn, uses the base_url from your config file.
Make sure your $config['base_url'] is set to your domain (with trailing slash) in the application/config/config.php file.
$config['base_url'] = 'http://jonhopkins.net/';

jQuery Ajax Submit issues

the Form
<article id="signup-form">
<form id="signupform" method="post" action="signup.php" accept-charset="utf-8">
<label for="email">Email Address</label>
<input type="text" id="email" name="email"/>
<input type="image" src="images/btn_signup.png" value="Sign up" alt="Sign up"/>
</form>
<br />
</article>
the Javascript
$(document).ready(function () {
$('#signupform').submit(function () {
var email = $('#email').val();
if (email != 0) {
if (isValidEmailAddress(email)) {
$(this).ajaxSubmit(options);
} else {
alert("Please Enter a Valid Email Address");
}
} else {
alert("Please Enter a an Email Address");
}
return false;
});
var options = {
success: showResponse,
dataType: 'json',
resetForm: true
};
function showResponse(responseText, statusText, xhr, $form) {
if (responseText == 'false') {
alert("Please try again. We could not sign you up.");
}
if (responseText == 'true') {
alert("Success");
}
}
});
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
}
i get the folowing error and the form submits and goes to the signup.php
You can prevent the forms default event by altering your call
$('#signupform').submit(function (event) and the entering event.preventDefault