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>';
}
?>
Related
At the moment I have a working contact form. I'd like to hide the "submit" button of my form when the form is sent successfully and then display a success message.
At the moment it redirects, which I've left for the purpose of this request.
I've tried multiple solutions, tweaking of the js but js sure isn't my strong point. I've left the CSS in also for the purpose of this question as I believe that will be the route I need to go down.
<< ? php
if (empty($_POST) === false) {
session_start();
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$errors = array();
if (isset($_POST['name'], $_POST['email'], $_POST['message'])) {
$fields = array(
'name' => $_POST['name'],
'email' => $_POST['email'],
'message' => $_POST['message']
);
foreach($fields as $field => $data) {
if (empty($data)) {
//$errors[] = "The " . $field . " is required";
$errors[] = "Please fill-in the form correctly";
break 1;
}
}
if (empty($errors) === true) {
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errors[] = "Invalid e-mail address";
}
}
if (empty($errors) === true) {
$name = test_input($_POST['name']);
$email = test_input($_POST['email']);
$message = test_input($_POST['message']);
$to = "example#example.com";
$subject = "example | You have a new message from ".$name;
$body = ......
if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['message'])) {
$data = $_POST['name'].
' == Email: '.$_POST['email'].
' Message: '.$_POST['message'].
"\r\n";
$ret = file_put_contents('entries.log', $data, FILE_APPEND | LOCK_EX);
if ($ret === false) {
die('There was an error writing this file');
} else {
echo "$ret bytes written to file";
}
} else {
header('location: ../sendmail/redirect.html');
}
$headers = "MIME-Version: 1.0".
"\r
#thank-you-message {
display: none;
}
#thank-you-message.show {
display: block;
}
<form action="/sendmail.php" method="post" onsubmit="return checkform(this);">
<input type="text" name="name" id="" autocomplete="off" placeholder="Name" required><br>
<input type="email" name="email" id="" autocomplete="off" placeholder="E-mail" required><br>
<textarea name="message" id="" cols="30" rows="10" placeholder="Type Your Message" required></textarea>
<button type="submit">Send</button>
</form>
<p id="thank-you-message">Thank you for contacting us. We will be in touch with you soon.</p>
You can use JavaScript to hide this button or generate this site by using PHP.
You have two possibilities, cookies or sessions.
Check if cookie or session is set, if not display the button or form, if is set hide button or form.
This can be done within a If/Else condition and a simple „print“ function.
Like (PHP)
IF (isset xxx = true) {
// print nothing
// redirect to page xxx.html
// or print Text like Lorem Ipsum
}
else {
print '<form method=“POST“ action=“form.php“> … </form>';
}
After submit the form you have to set a session or cookie in „form.php“.
When a user come back to this site, the site will check the cookie or session and print the form or not.
You have to change the IF/Else condition to your needs.
You can also print a „Thank you page“ or something else you want, you can also redirect to a other page by the header function within php.
Quick fix, you could try structuring your code in this format if using PHP
function save() {
$('.btn-danger').hide()
var number_i = $('#number_i').text();
var date_s = $('#date_s').text();
var name_p = "<?php echo $_POST['product_name']; ?>";
if (number_i != '___') {
$.post('saveEntry.php', {number: number_i, date: date_s, name: name_p}, function() {
$('#confirmation').text('Info: the data was saved!');
$('#confirmation').attr('class', 'alert alert-success');
})
} else {
alert('Introdu Numar Bon Fiscal!');
}
};
No need for JS for this. Assuming your form is parsing properly, you can add the following styles to your stylesheet.
#thank-you-message {
display: none;
}
button:focus ~ #thank-you-message {
display: block;
}
I removed your PHP and the rest of your form so that you can see a demonstration. See below:
Edit ~ added sample JS for the button to change text upon form submission. (Doesn't affect p displaying on button click)
function form_success() {
document.getElementById("myform").submit();
document.getElementById("btn").innerHTML = "Sent!";
}
#thank-you-message {
display: none;
}
button:focus {
background-color: green;
color: white;
}
button:focus~#thank-you-message {
display: block;
}
<form action="/sendmail.php" method="post" onsubmit="return checkform(this);" id="myform">
<input type="text" name="name" id="" autocomplete="off" placeholder="Name" required><br>
<input type="email" name="email" id="" autocomplete="off" placeholder="E-mail" required><br>
<textarea name="message" id="" cols="30" rows="10" placeholder="Type Your Message" required></textarea><br>
<button type="submit" id="btn" onclick="form_success()">Send</button>
<p id="thank-you-message">Thank you for contacting us. We will be in touch with you soon.</p>
</form>
I am wanting to know if you can add more than one url in the action attribute in the form element? I know a lot of people are asking that but the ones I am adding in are: a php self and a mailto action. This is a feedback form so when any one sends some feedback it should check the php of validation of it and send a email at the same time once the submit button is clicked. But I tested that but when I clicked the submit button it came up as an error page. Can any one please help me?
HTML:
<form action="<?php echo htmlspecialchars($_server['php_self']);?>
, mailto:example#gmail.com" method="post" name="feedbackForm" id="ff" class="feedback"> <label for="first">First Name:</label>
<input type="text" id="first" name="fname" class="namef" placeholder="First Name" required="required"/><span class="error"><?php echo $fnameErr;?>
</span><br/>
<label for="last">Last Name:</label>
<input type="text" id="last" name="lname" class="namel" placeholder="Last Name" required="required"/><span class="error"><?php echo $lnameErr;?>
</span><br/>
<label for="mail">Email:</label>
<input type="email" id="mail" name="email" class="u-email" placeholder="any email is fine!" required="required"/><span class="error"><?php echo
$emailErr;?>
</span><br/>
<label for="yearLevel">Year Level:</label>
<select name="yearLevel" id="yearLevel" onchange="MM_jumpMenu('parent',this,0)">
<option>Year 8</option>
<option>Year 9</option>
<option>Year 10</option>
<option>Year 11</option>
<option>Year 12</option>
<option>Uni Student</option>
<option>Other</option>
</select>
<label for"comment">Comment:</label>
<textarea id="comment" name="comment" class="userComment" rows="12" cols="" "55" ">
</textarea><br/><br/>
<input type="submit" name="submitFeed" id="subff" class="sub" onclick="ask()" style="margin-left:20%;"/>
</form>
PHP:
<?php
//feedback form validation code
//start
//variables
$fnameErr = $lnameErr = $yearleErr = $emailErr = "";
$firstName = $lastName = $comment = $yearLevel = $email = "";
//the function of validation
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["fname"])) {
$fnameErr = "* Your first name is required!";
} else {
$firstName = test_input($_POST["fname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z]*$/", $firstName)) {
$fnameErr = "* Only letters and white space allowed!";
}
}
if (empty($_POST["lname"])) {
$lnameErr = "* Your last name is required!";
} else {
$lastName = test_input($_POST["lname"]);
if (!preg_match("/^[a-zA-Z]*$/", $lastName)) {
$lnameErr = "* Only letters and white space allowed!";
}
}
if(empty($_POST["comment"])) {
$comment = "* the comment box is required!";
} else {
$comment = test_input($_post["comment"]);
}
if (empty($_POST["email"])) {
$emailErr = "* Your email is required!";
} else {
$email = test_input($_POST["email"]);
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "* Invalid Email Format!";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
//end
?>
JS script for a confirm when the user clicks submit. so it makes sense to the form.
<script type="text/javascript">
//confrim before submitting.
function ask() {
var box = confirm("Are you sure you want to send this feeback? If yes
that you are sure click ok or if not then click canel to edit it.");
if (box == true) {
document.getElementById('firstPart').style.display = "none";
document.getElementById('nextPart').style.display = "block";
console.log("Thanks for sending your feedback");
return true;
} else {
console.log("edit!");
return false;
}
}
</script>
You couldn't add multiple actions in the form action, You should send the form to a PHP file and then after validating, send the email by PHP mail function or other libraries like PHPmailer etc.
Simple answer: No, you cannot add multiple actions for tag, how you would the distinguish between which one to choose?
If you need to select different actions according to some configuration on form choices (or whatever), use Javascript to set new action of form.
In your case, use mail PHP function to send mail from PHP script when you pass your validation.
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post" name="feedbackForm" id="ff" class="feedback">
and then in PHP
mail('somebody#example.com', 'Subject', 'Body', optionalHeaders);
You can't do it, but you can call mailto inside your ask() like,
function ask() {
var box = confirm("Are you sure you want to send this feeback? If yes
that you are sure click ok or if not then click canel to edit it.");
if (box == true) {
document.getElementById('firstPart').style.display = "none";
document.getElementById('nextPart').style.display = "block";
console.log("Thanks for sending your feedback");
// add mailto here
myWindow=window.open("mailto:example#gmail.com");
myWindow.close();
return true;
} else {
console.log("edit!");
return false;
}
}
And change form action like,
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post" ...>
....
</form>
I'm fairly new to PHP and I'm having trouble sending test emails out from my local host.
I have a 3 field form where I'm hoping that I can have a user submit the form & be able to see a success message without the page refreshing. I get the error message that I have set in the code but for some reason, I'm unable to actually get the emails to send/have a success message appear.
Here's my code:
js
jQuery( document ).ready( function( $ ) {
var form = $('#ajax-contact');
var formMessages = $('#form-messages');
$(form).submit(function(e) {
e.preventDefault();
var formData = $(form).serialize();
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
$(formMessages).text(response);
$('#name, #email, #number').val('');
})
.fail(function(data) {
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
});
mailer.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$number = trim($_POST["number"]);
if ( empty($name) OR empty($number) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
http_response_code(400);
echo "Sorry, there seems to be a problem submitting your details, please try again or contacts us";
exit;
}
$recipient = "example#example.co.uk";
$subject = "$name has given you their details to call them back";
$email_content = "
<html>
<style>
body {
background-color: white;
}
.email-container{
background-color:#c1c1c1;
max-width:400px;
margin:0 auto;
padding:30px 10px;
border-radius:10px;
border: 2px solid #515151;
}
</style>
<body>
<div class="email-container">
Dear example, <br />
<br />
A potential client has requested a call back. Their details are as follows: <br />
<br />
Name: $name\n <br />
Email: $email\n\n <br />
Telephone: \n$numer\n
</div>
</body>
</html>"
$email_headers = "From: $name <$email>";
if (mail($recipient, $subject, $email_content, $email_headers)) {
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
http_response_code(500);
echo "Sorry, there seems to be a problem submitting your details, please try again or contacts us";
}
} else {
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
HTML
<form class="requestcall-form" id="ajax-contact" method="post" action="mailer.php">
<input type="text" id="name" name="name" placeholder="Full Name" required>
<input type="text" id="email" name="email" placeholder="Email Address" required>
<input type="text" id="number" name="number" placeholder="Contact number" required>
<input class="submit" type="submit" name="submit" value="Submit">
</form>
<div id="form-messages"></div>
there is something wrong with how you output $email_content. String is not formatted correctly
check the <div class="email-container"> and change it to <div class='email-container'>
also, add a (;) after your $email_content
The other answer is correct, I thought I'd offer a better solution for dealing with large blocks of text, heredoc strings. No worrying about unescaped quotes ruining your day. Using this, your code would look like this:
...
$recipient = "example#example.co.uk";
$subject = "$name has given you their details to call them back";
$email_content = <<< HTML
<html>
<style>
body {
background-color: white;
}
.email-container{
background-color:#c1c1c1;
max-width:400px;
margin:0 auto;
padding:30px 10px;
border-radius:10px;
border: 2px solid #515151;
}
</style>
<body>
<div class="email-container">
Dear example, <br />
<br />
A potential client has requested a call back. Their details are as follows: <br />
<br />
Name: $name <br />
Email: $email <br />
Telephone: $numer
</div>
</body>
</html>
HTML;
$email_headers = "From: $name <$email>";
...
I have looked at a few solutions on here trying different ways of doing this but none are working for me.
Here is my form:
<form action="<?PHP echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="POST" name="contact" role="form">
<?PHP //if error has occured then echo the error in red
if(isset($errorMsg) && $errorMsg) {
echo "<p style=\"color: red;\">*",htmlspecialchars($errorMsg),"</p>\n\n";
}
?>
<label for="name"><b>Name:</b></label>
<input type="text" name="name" id="name" placeholder="Enter full name" value="<?PHP if(isset($_POST['name'])) echo htmlspecialchars($_POST['name']); ?>">
<label for="email"><b>Email:</b></label>
<input type="text" name="email" id="email" placeholder="Enter a valid email address..." value="<?PHP if(isset($_POST['email'])) echo htmlspecialchars($_POST['email']); ?>">
<label><b>Subject:</b></label>
<input type="text" name="subject" id="subject" placeholder="Please enter a subject matter" value="<?PHP if(isset($_POST['subject'])) echo htmlspecialchars($_POST['subject']); ?>">
<label for="query"><b>Query:</b></label>
<textarea id="query" placeholder="Please write your message here..." name="query" value="<?PHP if(isset($_POST['query']))echo htmlspecialchars($_POST['query']);?>">
</textarea>
<input type="submit" name="submit" id="submit" value="Submit" class="style-button">
</form>
I am using a one page website so the contact form is at the bottom of the page.
How can i show a thank you message inside the form when it has been submitted and went through validation - without the page going back to the top?
PHP code:
<?php
// if submit is clicked then assign variables
if($_POST && isset($_POST['submit'], $_POST['name'], $_POST['email'], $_POST['subject'], $_POST['query'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$query = $_POST['query'];
//making sure the page goes to the contact form with the errors instead of the top of the page
if(!isset($_POST['$errorMsg']))
{
?>
<script>
window.location.hash = '#contact-form';
</script>
<?php
}
// if name is not entered then display errorMsg
if (!$name) {
$errorMsg = "Please enter your name";
}
// if email is not entered then display errorMsg
elseif (!$email || !preg_match("/^\S+#\S+$/", $email)) {
$errorMsg = "Please enter a valid email address";
}
// If the subject has not entered then display errorMsg
elseif (!$subject) {
$errorMsg = "Please enter a subject";
}
// if query is not entered then display errorMsg
elseif (!$query) {
$errorMsg = "Please enter your query";
}
else {
//send email and redirect to confirmation page
$toemail = "email#example.com";
$subject2 = "Message recieved from ". $name."";
$headers = "MIME-Version: 1.0\n"
."From: \"".$name."\" <".$email.">\n"
."Content-type: text/html; charset-iso-8859-1\n";
$body = "Email: ".$email."<br>\n"
."Subject: ".$subject."<br>\n"
."email: ".$email."<br>\n"
."query: ".$query."<br>\n"
;
mail($toemail, $subject, $body, $headers);
if(mail($toemail, $subject, $body, $headers)){
$toemail =".$email";
$subject = "Confirmation Email";
$body = "Your email has been sent";
header("location: index.php");
}
}}
?>
Somewhere, hopefully above the HTML, you are processing the form post. So you should be setting $errorMsg in there.
Rule of thumb for a self-submitting web page: logic before view. Also, to avoid the if() statement, initialize $errorMsg on every page load.
O.k I have seen similar questions but can't seem to make it work. I would like that when the form is submitted the fields get cleared.
This is my PHP:
<?php $name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$formcontent="From: $name \n Message: $message";
$recipient = "EMAIL ADDRESS";
$subject = "Unriddle contact form";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo '<p style="margin-top: 1em; font-color: #66CC00;">Thank you!</p>'; ?>
This my HTML:
<form action="mail.php" method="post">
<a class="form-row">
<p>Name</p>
<input id="iname" type="text" class="text-input required default" name="name" value="" />
</a>
<a class="form-row">
<p>Email</p>
<input id="email" type="text" class="text-input required email default" name="email" value="" />
</a>
<a class="form-row">
<p>Message</p>
<textarea id="message" class="text-area" name="message" cols="40" rows="8"></textarea>
</a>
<br />
<input class="btn-submit" type="submit" value="Send" name="submit" />
This is my JS
jQuery(document).ready(function($) {
var $loading = $('<div class="loading"><img src="/js/loading.gif" alt="" /></div>');
$(".default").each(function(){
var defaultVal = $(this).attr('title');
$(this).focus(function(){
if ($(this).val() == defaultVal){
$(this).removeClass('active').val('');
}
});
$(this).blur(function() {
if ($(this).val() == ''){
$(this).addClass('active').val(defaultVal);
}
})
.blur().addClass('active');
});
$('.btn-submit').click(function(e){
var $formId = $(this).parents('form');
var formAction = $formId.attr('action');
defaulttextRemove();
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
$('li',$formId).removeClass('error');
$('span.error').remove();
$('.required',$formId).each(function(){
var inputVal = $(this).val();
var $parentTag = $(this).parent();
if(inputVal == ''){
$parentTag.addClass('error').append('<span class="error">Required field</span>');
}
if($(this).hasClass('email') == true){
if(!emailReg.test(inputVal)){
$parentTag.addClass('error').append('<span class="error">Enter a valid email address</span>');
}
}
});
if ($('span.error').length == "0") {
$formId.append($loading.clone());
$('fieldset',$formId).hide();
$.post(formAction, $formId.serialize(),function(data){
$('.loading').remove();
$formId.append(data).fadeIn();
});
}
e.preventDefault();
});
});
function defaulttextRemove(){
$('.default').each(function(){
var defaultVal = $(this).attr('title');
if ($(this).val() == defaultVal){
$(this).val('');
}
});
}
Is there a simple way of doing this ? What line of code do I need to add and where ? If you can help me that would be great, but please be specific as to where I should add the line of code.
Power to you! Thanks
Add reset on success of your ajax request or if you want to clear every time on submit add at the end .
if ($('span.error').length == "0") {
$formId.append($loading.clone());
$('fieldset',$formId).hide();
$.post(formAction, $formId.serialize(),function(data){
$('.loading').remove();
$formId.append(data).fadeIn();
$formId.reset();// to reset
});
}