validation form with php - safari site - javascript

Need quick help, if anyone can...
I have a quite simple html one page with form
and I'm trying to validate it with php (check blanks and verify email)
for some reason something going wrong and it doesn't show me anything
on action form
anyone have any idea? will really help me a lot.
the icons present the obvious (the text is hebrew)
(if someone knows how to validate phone, bless you as well)
the html:
<!DOCTYPE html>
<html lang="he" dir="rtl">
<head>
<title>Safari Company</title>
<meta charset="utf-8"/>
<link rel="stylesheet" type="text/css" href="styles.css">
<script src="js/script.js"></script>
</head>
<body>
<div id="top-wrapper">
<div id="top-background">
<p class="image-text">.אפריקה. נקודת מבט חדשה</p>
<p class="credit-english">Ziv Koren</p>
</div>
</div>
<div id="costumer-wrapper">
<div id="info-for-client">
<p class="secondary-text">הדרך לאפריקה מתחילה בטיסה ישירה לטנזניה</p>
<p class="offer-text">פסח 2015 <span>|</span> 9 ימים מלאים</p>
<p class="ratz-border-above">ספארי קומפני בטיסת (סאנדור) אל-על ישירה לטנזניה וחזרה ישירות מזנזיבר. מבחר תוכניות ספארי מותאמות באופן אישי.</p>
<p class="strong">תמיד אמרתם שפעם תעשו את זה. עכשיו זה הזמן</p>
<p class="secondary-text">למידע נוסף, התאמת ספארי אישי </br> והזמנות 03-5617021</p>
</div>
<form method="post" action="confirmation.php" name="myForm" onsubmit="return validate();">
<input type="text" class="name" name="Name" placeholder="שם">
<input type="text" class="email" name="Email" placeholder="דוא״ל" >
<input type="text" class="phone" name="Phone" placeholder="טלפון" >
<textarea placeholder="הערות"></textarea>
<input type="checkbox" > ארצה לקבל עדכונים וחדשות
<button type="submit"> שלח</button>
</form>
<p class="hebrew-credit">זהות ושפה - מוסנזון פורת</p>
</div>
<div id="bottom-background">
<div id="bottom-image"> </div>
<p class="credit-english"></p>
</div>
<div id="footer-wrapper">
<footer>
<p>ספארי, בשפה הסווהילית, פירושו מסע, בשפה שלנו, מסע פירושו יציאה לדרך של גילויים חדשים, מראות, ריחות, טעמים.</br>
תחושה שאין דומה לה. לגלות את אפריקה, בכל פעם מחדש, כבר 20 שנה. נשמח להיות הדרך שלכם לאפריקה.</p>
<p class="adress-border-above"> סעדיה גאון 24, תל אביב טל. 03-5617021 פקס. 15335468614 <span> | www.safaricompany.co.il | info#safaricompany.co.il</span></p>
<img src="images/logo.png">
</footer>
</div>
</body>
<script>
function validate(){
if( document.myForm.Name.value == "" )
{
alert( "Please provide your name" );
document.myForm.Name.focus() ;
return false;
}
if( document.myForm.Email.value == "" )
{
alert( "Please provide your Email" );
document.myForm.Email.focus() ;
return false;
}
if( document.myForm.Phone.value == "" )
{
alert( "Please provide your Phone" );
document.myForm.Phone.focus() ;
return false;
}
return true;
}
</script>
</html>
the php:(confirmation.php)
<?php
if($_SERVER["REQUEST_METHOD"] == "POST"){
$name = trim($_POST["Name"]);
$email = trim($_POST["Email"]);
$phone = trim($_POST["Phone"]);
if( $name == "" || $email=="" || $phone==""){
echo "Please fill name, email and phone";
exit;
}
require_once("Inc/phpmailer/class.phpmailer.php");
$mail = new PHPMailer();
if(!$mail -> ValidateAddress($email)){
echo "You must specify a valid email.";
exit;
}
?>
<html>
<body>
Welcome <?php echo $_POST["Name"]; ?><br>
Your email address is: <?php echo $_POST["Email"]; ?>
</body>
</html>

It probably is overkill to use a custom library just to verify an email address. You could use https://secure.php.net/filter_var with the FILTER_VALIDATE_EMAIL filter. As far as I know, there is no real way of validating phone numbers.
That being said, your PHP error is that you do not close the if statement started on line 2. That causes an unexpected end, as the compiler still wants a closing accolade for your if statement.
EDIT: There is a very good SO answer for validating phone numbers.

There are a few things going on with the approach to your script.
Here is what I came up with that works on the script page.
<?php
if($_SERVER["REQUEST_METHOD"] == "POST") {
$name = trim($_POST["Name"]);
$email = trim($_POST["Email"]);
$phone = trim($_POST["Phone"]);
if( $name == "" || $email=="" || $phone==""){
$error = "Please fill name, email and phone";
}
}
else {
$error = "ERROR if someone came here directly";
}
?>
<html>
<body>
<?php if(isset($error)): ?>
<p><?php echo $error; ?></p>
<?php else: ?>
Welcome <?php echo $_POST["Name"]; ?><br>
Your email address is: <?php echo $_POST["Email"]; ?>
<?php endif; ?>
</body>
</html>
EDIT: To address the email validation you would use this to check if true or false:
This method checks if the email is NOT valid.
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailError = "Invalid email";
}

Related

My page does not stay the same page when I click the option submit

I'm a little new here. I tried to make my website on my own and although it is almost finished, I can not solve the problem of sending information in my contact form.
The page is this: ramproducciones.pe (it's in Spanish)
If they go towards the end they find the contact form, even if they fill the data correctly, the email is sent but the next thing is that a blank page is given. What I want is that you get a message that says Thank you! Your message has been sent but I do not know how to do it. I have tried to copy many codes and I currently have this:
<!-- contacto-->
<section class="contact" id="contact">
<h1>Contacto</h1>
<hr/>
<div class="content">
<div class="form">
<form method="post" action="mail.php" name="contact">
<div class="column">NOMBRE<br/><br/>
<input name="name" id="name" value="" />
</div>
<div class="column-2">E-MAIL<br/><br/>
<input name="email" id="email" value="" />
</div>
<div class="column-3">MENSAJE<br/><br/>
<textarea id="message" name="message" ></textarea>
</div>
<div class="button">
<span><input class="submit" id="submit" name="submit" type="submit" value="ENVIAR"></span>
</div>
<div id="dialog-message" title="Thank You">
<p>¡Gracias! Tu mensaje ha sido enviado, te responderemos lo antes posible.</p>
</div>
</form>
</div>
<div class="contact-text">
No dudes en solicitarnos información.<br/><br/>
<strong>RAM Producciones</strong><br/><br/>
e-mail: <strong>info#ramproducciones.com</strong>
<br/><br/>
<img src=img/social/Facebook.png />
<img src=img/social/Vimeo.png />
<img src=img/social/Behance.png />
<img src=img/social/Instagram.png />
<img src=img/social/Youtube.png />
</div>
</div>
</section>
AND THE PHP is
<?php
// define variables and set to empty values
$name_error = $email_error = "";
$name = $email = $message = $success = "";
//form is submitted with POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$name_error = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$name_error = "Solo ingresa letras y espacios.";
}
}
if (empty($_POST["email"])) {
$email_error = "Tu E-mail es necesario";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Formato de E-mail inválido";
}
}
if (empty($_POST["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
if ($name_error == '' and $email_error == '' and $phone_error == '' and $url_error == '' ){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$to = 'info#ramproducciones.pe';
$subject = 'Mail vía RAMPRODUCCIONES.PE';
if (mail($to, $subject, $message)){
$success = "¡Gracias! Tu mensaje ha sido enviado, te responderemos lo antes posible.";
$name = $email = $message = '';
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
However I still can not solve the problem.
It's your action. You're sending your page to another page called mail.php. Set the action to reload your current page when the form is submitted.
Try using
<form id='form' method='post' action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>'>
as an attribute in your form
In the top of your page where you run your code for successful form submission, hide the form then display your message.
echo "<style>#form{display:none}</style>";
echo "<p>Thank you for submitting</p>";
There are a lot of possibilities in your case. Clearshot66 has introduced one.
Another possibility would be to keep your mail.php page and after the sending of the e-mail, you could create a logic to send the user back to your main page and show him a message. This could be done as I show you below:
mail.php
header("Location: your_main_page.php?showMessage=1");
exit;
your_main_page.php
<?php
if ($_GET["showMessage"] == 1) {
echo "Thanks for your contact.";
}
?>
The above code should be put in the beggining of your main_page.php
This is another IDEA.
The best good practice is to send the form using some ajax request and handle the return of this request, but this is a little bit more sofisticated than the options that we pointed to you.
As #clearshot66 said, you are redirecting to mail.php. I understand, that the php page you mean is this file.
What Fredi -ii- saw, you forgot to echo $success.
Blank page happens, because there is no output.
Hope I helped.

php mail form on magento product page

I am trying to make a simple price match contact form on my product page in Magento. I have a separate php file but it doesn't seem to receive the commands from the view.phtml file.
this is the form code which is located inside /app/design/frontend/default/my_design/template/catalog/product/view.phtml
<div class="pricematcher">
<body class="body">
<div id="pricematch" style="display:none;">
<!-- Popup Div Starts Here -->
<div id="popupContact">
<!-- Contact Us Form -->
<form action="send_contact.php" id="form" method="post" name="form">
<img id="close" src="<?php echo $this->getSkinUrl(); ?>images/close.png" onclick="div_hide()"</img>
<h2 class="h2price">Price Match</h2>
<hr id="hrprice">
<input id="name" name="name" placeholder="Name" type="text">
<input id="email" name="email" placeholder="Email" type="text">
<input id="productname" name="productname" placeholder="<?php echo $_helper->productAttribute($_product, $_product->getName(), 'name') ?><?php echo $this->__(' PART #: ');?><?php echo $_helper->productAttribute($_product, nl2br($_product->getSku()), 'sku') ?>" type="text" readonly>
<input id="competitor" name="competitor" placeholder="Competitor Product Link" type="text">
<textarea id="msg" name="msg" placeholder="Message"></textarea>
Submit
</form>
</div>
<!-- Popup Div Ends Here -->
</div>
<!-- Display Popup Button -->
</body>
</div>
<img id="popup" src="<?php echo $this->getSkinUrl(); ?>images/price-match.png" onclick="div_show()"</img>
this is the javascript which makes the form pop up and display
// Validating Empty Field
function check_empty() {
if (document.getElementById('name').value == "" || document.getElementById('email').value == "" || document.getElementById('msg').value == "") {
alert("Fill All Fields !");
} else {
document.getElementById('form').submit();
alert("Thank You for submitting a Price Match inquiry");
}
}
//Function to Hide Price Match
function div_hide(){
document.getElementById('pricematch').style.display = "none";
}
//Function To Display Price Match
function div_show() {
document.getElementById('pricematch').style.display = "block";
}
this is the php file that the form action should send to send_contact.php file located in the same directory as view.phtml
<?php
$subject = "Price Match";
$message = $_POST['msg'];
$name = $_POST['name'];
$product = $_POST['productname'];
$competitor = $_POST['competitor'];
$mail_from = $_POST['email'];
// Enter Your email Adress
$to = "myemail#email.com";
$body = "$message, $competitor, $product";
$send_contact = mail($to,$subject,$body, "From: " . $mail_from);
//Check if message sent
if ($send_contact){
echo "we recieved";
}
else {
echo "error";
}
?>
Every thing works when I make this in a seperate folder on my server and execute outside of magento.
You should put send_contact.php at magento's root directory.
I think you can create an action in ProductController.php,for example,postEmailAction, then in the postEmailAction,you can get the data from the form:
$message = $_POST['msg'];
$name = $_POST['name'];
$product = $_POST['productname'];
$competitor = $_POST['competitor'];
$mail_from = $_POST['email'];
, flow the code:
`
$mail = Mage::getModel('core/email');
$mail->setToName('YourStore Admin');
$mail->setToEmail($toEmail);
$mail->setBody($body);
$mail->setSubject('YourStore: New Product Review');
$mail->setFromEmail('donotreply#yourstore.com');
$mail->setFromName("YourStore");
$mail->setType('html');
try {
$mail->send();
}
catch (Exception $e) {
Mage::logException($e);
}
`
the action url will be the product controller + the action name;
Hope this will help you.

Javascript inside php echo not executing?

<?php
//Clear the cache for form values
header('Cache-Control: no store, no-cache, must-revalidate');
header('Cache-Control: no store, no-cache, must-revalidate');
header('Pragma: no-cache');
//Load up functions
include "recon.php";
//Create the PHP Self Function
$username = $nohours = $noitem = $ipaddr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = filter_input(INPUT_POST, "username", FILTER_SANITIZE_STRING);
$nohours = filter_input(INPUT_POST, "hours", FILTER_SANITIZE_NUMBER_INT);
$noitem = 0;
$xnoitem = filter_input(INPUT_POST, "itemselect", FILTER_SANITIZE_STRING);
if ($xnoitem === "item1") {
$noitem = 1;
}
$ipaddr = get_client_ip();
if(!empty($username)){
echo "Username is not null";
}
else{
echo '<script type="text/javascript">document.getElementById("warning").innerHTML = "New text!";</script>';
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title> GGG Time Form </title>
<script type="text/javascript">
function outputUpdate(hours)
{
document.querySelector('#nohours').value = hours;
document.getElementById("total").innerHTML = "$" + hours * 3.75;
document.getElementById("item1").checked = false;
}
function xitem1()
{
document.getElementById("total").innerHTML = "$16";
}
</script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div>
<div>
<h1 class="ctext">GGG Time Order Form</h1>
</div>
<div>
<p id="warning"></p>
</div>
</div>
<hr>
<div>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
(Enter your username you login with at GGG) Username:<span style="color:red;">*</span> <input type="text" name="username">
<br>
<br>
<label for="hourslider">Number of hours you would like to purchase: </label>
<input type="range" name="hours" min="1" max="24" value="12" id="hourslider" oninput="outputUpdate(value)">
<output for="hourslider" id="nohours">12</output>
<br>
<br>
<h3> Or select one of our packages below </h3>
<br>
<input type="radio" name="itemselect" value="item1" id="item1" onclick="xitem1()"> Day Pass $16.00
<hr>
<h3> Total payment owed: <p id="total">$0</p></h3>
<input type="submit">
<hr>
</form>
</div>
<div id="ipbox">
<span>For security purposes your ip address is being logged: <?php echo get_client_ip(); ?></span>
</div>
<div>
</div>
</body>
</html>
So on that logical statement below this text ( Also located in the code above) I'm wondering why when I echo out the javascript it's not changing the contents of the <p> element with the id of warning. I've tried looking everywhere for my answer and I'm sorry if this is a duplicate but any help would be appreciated...
if(!empty($username)){
echo "Username is not null";
}
else{
echo '<script type="text/javascript">document.getElementById("warning").innerHTML = "New text!";</script>';
}
"your basic problem is that it is executing, but none of your document has loaded yet. there is no element with the id of warning at the point your javascript is being loaded and executed" ~ Watcher

Send PHP errors back to index

So I have an index.php and a r.php. R.php is the registration part. And index.php is the actual form. My question is how can I have errors from r.php be send back to index.php if they exist. So instead of displaying errors on r.php I want them on index.php and prevent the form from advancing.
Here's the index.php
<!DOCTYPE html>
<html>
<body>
<form method="post" action="r.php">
<input type="text" name="name" placeholder="Name">
<input type="submit">
</form>
</body>
Its all very simple. Now here's r.php
<?php
$name = $_POST['name'];
if ($name < 3){
//display error
}
else {
//proceed
}
?>
Should I do this with JS? Or this there a better way.
One way is to use sessions:
<?php session_start(); ?>
<!DOCTYPE html>
<html>
<body>
<?php echo isset($_SESSION['message']) ? $_SESSION['message'] : ''; ?>
<form method="post" action="r.php">
<input type="text" name="name" placeholder="Name">
<input type="submit">
</form>
</body>
<?php
session_start();
unset($_SESSION['message']);
$name = $_POST['name'];
if ($name < 3){ // you probably want strlen($name) < 3
$_SESSION['message'] = 'error';
header('Location: index.php');
exit;
}
else {
//proceed
}
?>
Other than sessions you could redirect back with a query string and use that:
header('Location: index.php?message=' . urlencode('some kind of error');
Then:
<?php echo isset($_GET['message']) ? $_GET['message'] : ''; ?>
Using a single script for this would be easier, just put this all in one file, and check to see if the form has been submitted. If the form has been submitted, you an just include the variables you want straight away.
This is pretty crude, but it gives you an idea of where you can go with this:
<?php
if (isset($_POST['name'])) {
// Begin processing form stuff
$name = $_POST['name'];
// Initialise error variable
$error = null;
if ($name < 3) {
// Display error, for example:
$error = 'Name is less than 3';
} else {
// Proceed
}
}
?>
<!DOCTYPE html>
<html>
<body>
<?php if ( ! empty($error)) { ?>
<p><?php echo $error; ?></p>
<?php } ?>
<form method="post" action="r.php">
<input type="text" name="name" placeholder="Name">
<input type="submit">
</form>
</body>
</html>
<!DOCTYPE html>
<html>
<?php
$msg = '';
if(isset($_GET['e'])
{
$msg = "Error! Input not valid.";
}
?>
<body>
<?php
if($msg!='')
{
echo "<font color='red'>".$msg."</font>";
}
?>
<form method="post" action="r.php">
<input type="text" name="name" placeholder="Name">
<input type="submit">
</form>
</body>
Just pass a variable e using GET request to the index page if an error is found.
<?php
$name = $_POST['name'];
if ($name < 3){
header("Location: index.php?e=error");
}
else {
//proceed
}
?>
GET request will send the variable e using the URL, and if e is found to be having a value, it means there was an error in r.php
Use javascript for simple form validation. In case you require some security stuff or db stuff, you can use session/cookie or use header function to go back.

Contact form does not validate on an iphone

The following contact form is not validating when submitting from an iphone...
It can be previewed here: loaistudio.com/contact
When I tried to submit the form without felling the fields, it opened a new blank page showing number 1 only on the top left side "which is not suppose to do at all" and actually sent the form empty... It does not do that on desktop.
I played around with the code trying to find the issue but no idea where is the problem! please help.
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
ob_start();
if(isset($_POST['name'])
&& isset($_POST['email'])
&& isset($_POST['message'])
&& isset($_POST['token'])){
if($_SESSION['token'] != $_POST['token']){
$response = "0";
} else {
$_SESSION['token'] = "";
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$to = "EMAIL GOES HERE";
$subject = "New Message From: $name";
$message = "$message";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$headers .= 'From: '.$email . "\r\n";
$mailed = ( mail($to, $subject, $message, $headers) );
if( isset($_POST['ajax']))$response = ($mailed) ? "1" :
"0"; else $response = ($mailed) ? "<h2>Success!</h2>" :
"<h2>Error! There was a problem with sending.</h2>";
echo $response;
}
} else {
echo "Form data error!";
}
ob_flush();
die();
}
?>
<!DOCTYPE html>
<html class="no-js">
<head>
<title>Contact us | Website</title>
</head>
<body>
<div class="wrapper" id="contactPage">
<div class="content">
<?php
$token = md5(uniqid(rand(), TRUE));
$_SESSION['token'] = $token;
?>
<!--Contact Form-->
<form action="contact.php" id="contactForm" method="post" name="contactForm">
<input name="token" type="hidden" value="<?php echo $token; ?>">
<input name="ajax" type="hidden" value="1">
<div class="name">
<p>Your Name</p>
<input name="name" placeholder="Enter Name" required="" type="text">
</div>
<div class="email">
<p>Email Address</p>
<input name="email" placeholder="Enter Email" required="" type="email">
</div>
<div class="message">
<p>Message</p>
<textarea name="message" required=""></textarea>
</div>
<button id="submit" type="submit">Send</button>
</form>
<script type="text/javascript">
$("#contactForm").submit(function(event) {
event.preventDefault();
$submit = $(this).find('button[id="submit"]');
var posting = $.post($(this).attr('action'), $('#contactForm').serialize());
posting.done(function(data) {
$('span.error').remove();
if (data == "1") {
$submit.text('Sent. Thank You!');
$submit.addClass("sent");
$submit.attr('disabled', 'disabled');
} else {
$submit.after('<span style="display: inline-block; padding: 15px 5px; color: #bd3d3d">Failed to send the message, please try again later.</span>');
$submit.text('Try Again');
}
});
});
</script>
</body>
</html>
you are adding jquery at the end of the html but you are using jquery before that, so javascript breaks with Uncaught ReferenceError: $ is not defined.
try moving this line to header:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$("#contactForm").submit(function(event) {
event.preventDefault();
$submit = $(this).find('button[id="submit"]');
var posting = $.post($(this).attr('action'), $('#contactForm').serialize());
posting.done(function(data) {
$('span.error').remove();
if (data == "1") {
$submit.text('Sent. Thank You!');
$submit.addClass("sent");
$submit.attr('disabled', 'disabled');
} else {
$submit.after('<span style="display: inline-block; padding: 15px 5px; color: #bd3d3d">Failed to send the message, please try again later.</span>');
$submit.text('Try Again');
}
});
});
</script>
This is code You have added AND THEN INCLUDED JQUERY, :) SO USE JQUERY IN HEADER !

Categories

Resources