Why is my page refreshing after submitting a form? - javascript

Problem
I will try to include as much information as possible without complicating things, but i have a problem where when i submit a form the page refreshes thus closing the tab with the form on. The user then needs to click on the tab again to view the feedback.
Background info.
I have one webpage using JavaScript to open and close "tabs" (divs), on one of these tabs i have a form which POST's the user inputted data to a php script which then sends the data to an email address and then redirects back the the original page. However when the script redirects back to the page the tab is closed thus making the user re-click on the tab to open it again to see the automated feedback from the script.
What i have checked
I have checked and it is not the redirect causing the refreshing as it still happens when the form POST's to itself.
The website in question
Does anyone have any ideas?
Here is the HTML for the form, which is in the enquiry 'tab'.
<div class='content one'>
<div id="contact-form" class="clearfix">
<P>Quick And Easy!</P>
<br/>
<P>Fill out our super swanky contact form below to get in touch with us! Please provide as much information as possible for us to help you with your enquiry.</P>
<br/>
<?php
//init variables
$cf = array();
$sr = false;
if(isset($_SESSION['cf_returndata'])){
$cf = $_SESSION['cf_returndata'];
$sr = true;
}
?>
<ul id="errors" class="<?php echo ($sr && !$cf['form_ok']) ? 'visible' : ''; ?>">
<li id="info">There were some problems with your form submission:</li>
<?php
if(isset($cf['errors']) && count($cf['errors']) > 0) :
foreach($cf['errors'] as $error) :
?>
<li><?php echo $error ?></li>
<?php
endforeach;
endif;
?>
</ul>
<p id="success" class="<?php echo ($sr && $cf['form_ok']) ? 'invisible' : ''; ?>">Now sit back and relax while we go to work on your behalf, we'll keep you updated with information on our results and if you have any questions then we welcome your calls or emails on 078675675446 or isaaclayne#southwestcarfinder.co.uk</p>
<form method="POST" action="process.php">
<label for="enquiry">Make: </label>
<select id="make" name="make">
<option value="Ford" <?php echo ($sr && !$cf['form_ok'] && $cf['posted_form_data']['make'] == 'Ford') ? "selected='selected'" : '' ?>>Ford</option>
<option value="BMW" <?php echo ($sr && !$cf['form_ok'] && $cf['posted_form_data']['make'] == 'BMW') ? "selected='selected'" : '' ?>>BMW</option>
<option value="Vauxhall" <?php echo ($sr && !$cf['form_ok'] && $cf['posted_form_data']['make'] == 'Vauxhall') ? "selected='selected'" : '' ?>>Vauxhall</option>
</select>
<label for="Model">Model: <span class="required">*</span></label>
<input type="text" id="model" name="model" value="<?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['model'] : '' ?>" placeholder="Model of Car" required autofocus />
<label for="name">Name: <span class="required">*</span></label>
<input type="text" id="name" name="name" value="<?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['name'] : '' ?>" placeholder="John Doe" required autofocus />
<label for="email">Email Address: <span class="required">*</span></label>
<input type="email" id="email" name="email" value="<?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['email'] : '' ?>" placeholder="johndoe#example.com" required />
<label for="telephone">Telephone: </label>
<input type="tel" id="telephone" name="telephone" value="<?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['telephone'] : '' ?>" />
<label for="Budget">Your Budget: </label>
<select id="enquiry" name="enquiry">
<option value="300 or less" <?php echo ($sr && !$cf['form_ok'] && $cf['posted_form_data']['enquiry'] == 'General') ? "selected='selected'" : '' ?>>£300 or less</option>
<option value="400 or more" <?php echo ($sr && !$cf['form_ok'] && $cf['posted_form_data']['enquiry'] == 'Sales') ? "selected='selected'" : '' ?>>£400</option>
<option value="500 or more" <?php echo ($sr && !$cf['form_ok'] && $cf['posted_form_data']['enquiry'] == 'Support') ? "selected='selected'" : '' ?>>£500 or more</option>
</select>
<label for="message">Additional Info: <span class="required">*</span></label>
<textarea id="message" name="message" placeholder="Your message must be greater than 20 charcters" required data-minlength="20"><?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['message'] : '' ?></textarea>
<span id="loading"></span>
<input type="submit" value="Find My Car!" id="submit-button" />
<p id="req-field-desc"><span class="required">*</span> indicates a required field</p>
</form>
<?php unset($_SESSION['cf_returndata']); ?>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>!window.jQuery && document.write(unescape('%3Cscript src="js/libs/jquery- 1.5.1.min.js"%3E%3C/script%3E'))</script>
<script src="js/plugins.js"></script>
<script src="js/script.js"></script>
<!--[if lt IE 7 ]>
<script src="js/libs/dd_belatedpng.js"></script>
<script> DD_belatedPNG.fix('img, .png_bg');</script>
<![endif]-->
</div>
PHP Script
<?php
if( isset($_POST) ){
//form validation vars
$formok = true;
$errors = array();
//sumbission data
$ipaddress = $_SERVER['REMOTE_ADDR'];
$date = date('d/m/Y');
$time = date('H:i:s');
//form data
$make = $_POST['make'];
$model = $_POST['model'];
$name = $_POST['name'];
$email = $_POST['email'];
$telephone = $_POST['telephone'];
$enquiry = $_POST['enquiry'];
$message = $_POST['message'];
//validate form data
//validate name is not empty
if(empty($name)){
$formok = false;
$errors[] = "You have not entered a name";
}
//validate email address is not empty
if(empty($email)){
$formok = false;
$errors[] = "You have not entered an email address";
//validate email address is valid
}elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$formok = false;
$errors[] = "You have not entered a valid email address";
}
//validate message is not empty
if(empty($message)){
$formok = false;
$errors[] = "You have not entered a message";
}
//validate message is greater than 20 charcters
elseif(strlen($message) < 20){
$formok = false;
$errors[] = "Your message must be greater than 20 characters";
}
//send email if all is ok
if($formok){
$headers = "From: Info#Columbus.com" . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$emailbody = "<p>You have recieved a new message from the enquiries form on your website.</p>
<p><strong>Name: </strong> {$name} </p>
<p><strong>Telephone: </strong> {$telephone} </p>
<p><strong>Email Address: </strong> {$email} </p>
<br/>
<p><strong>Make: </strong> {$make} </p>
<p><strong>Model: </strong> {$model} </p>
<p><strong>Budget: </strong> {$enquiry} </p>
<br/>
<p><strong>Message: </strong> {$message} </p>
<p>This message was sent from the IP Address: {$ipaddress} on {$date} at {$time}</p>";
mail("dancundy#hotmail.com","New Enquiry",$emailbody,$headers);
}
//what we need to return back to our form
$returndata = array(
'posted_form_data' => array(
'name' => $name,
'email' => $email,
'telephone' => $telephone,
'enquiry' => $enquiry,
'message' => $message
),
'form_ok' => $formok,
'errors' => $errors
);
//if this is not an ajax request
if(empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest'){
//set session variables
session_start();
$_SESSION['cf_returndata'] = $returndata;
//redirect back to form
//header('location:' . $_SERVER['HTTP_REFERER']);
header('Location: index.php#contact-form' );
}
}
?>

You are making a POST request when you submit the form. POST request by default travel through an HTTP request that the browser sends to the server, and therefore the browser needs to load the new data that causes the site to refresh.
If you want the browser to not refresh then you need to do an AJAX request using Javascript on the client side. You can use jQuery to accomplish this.

try this
$('form').submit(function(e)
{
e.preventDefault();
})

Thank you #saman and #gpopoteur,
Your answers are great and do work, just wasn't working on my testing server.
This is what got to work in the end.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script><script>
$('#form1').submit(function(e)
{
event.preventDefault();
$.ajax({
type : 'POST',
url : 'process.php',
data : $(this).serialize(),
success : function(response) {
}
});
});
What i did find is though that nothing is returned from the script. E.I any validation info or returned data? Not too much of a problem and i'll create a work around. Thank again

Related

Wordpress PHP Contact form - problem with displaying message about sent mail

I'm trying to develop a contact form for a language school website that runs on Wordpress.
Disclaimer: I'm about 6 months into coding, so please forgive me for being new to this. I'm developing my own theme and I wanted to limit usage of plugins to bare minimum for safety reasons - I prefer to learn how to write stuff myself instead on relying on updates of a third-party plus the courses I follow on Wordpress dev listed it as a good practice to avoid unnecessary plugins.
Update: I tried implementing plugins, but they either broke my page or didn't work anyway.
The problem is listed below in bold.
What I want to achieve:
Simple contact form that takes following info: name, email, course, phone (optional) and a message.
Validate the form if user provided correct info - I can't make the
user provide valid info, but at least I want to lock number into
numbers only range and check if email is correct.
Check if user is human (Captcha).
Send the email to my address and provide a copy to the sender.
Inform the user whether the action was a success or a failure.
What I succeeded with:
Mail gets sent.
Captacha seems to be working and filtering out attempts that do not click on it.
What 'kinda works':
The PHP doesn't seem to validate the form. I used HTML type and require instead, but I've read that solution is not ideal. I tried to use JS to write some functions that would prevent unwanted input, but I couldn't get it to work properly. I decided to ask the question first in case it might be a dead end. JS seems to be working on my Wordpress as I'm using Bootstrap and some custom JS for certain features so I'm pretty sure the code gets executed, but I wanted to ask first if that's the correct way of approach it before I invest my time in it.
What I have a problem with:
It is imperative to me that the user gets feedback from the page whether the email has been sent or not for obvious business-client communication reasons. I tried two solutions found on SO:
Injecting JS alert into PHP's echo inside conditional (JS doesn't get executed)
Using header method to redirect into thank-you.page that informs about success or error.page that
informs about a failure and recommends another avenue of contact
What went wrong: the second solution got executed properly, the user gets redirected to site.com/thank-you or site.com/error, however the browser crashes due to 'too many redirects'.
I tried googling, I tried different solutions from tutorials. What would be your recommendation?
My code:
<?php
$nameErr = $emailErr = $courseErr = $phoneErr = "";
$name = $email = $course = $comment = $phone = "";
$thank_you = wp_redirect( '"'.home_url().'/thank-you"', 301 );
$error = wp_redirect( '"'.home_url().'/error', 301 );
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Give name";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Need email";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Email incorrect";
}
}
if (empty($_POST["phone"])) {
$phone = "";
} else {
$phone = test_input($_POST["phone"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!is_numeric($number)) {
$phoneErr = "Bad number";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["course"])) {
$courseErr = "Pick course";
} else {
$course = test_input($_POST["course"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if(!empty($_POST['g-recaptcha-response']))
{
$secret = 'mySecretKey';
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
$responseData = json_decode($verifyResponse);
if($responseData->success)
$message = "g-recaptcha verified successfully";
if(isset($_POST['submit'])){
$to = "myEmail#mail.org"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$name = $_POST['name'];
$course = $_POST['course'];
$phone = $_POST['phone'];
$comment = "Form submission";
$comment2 = "Copy of your form submission";
$message = "Name:" . $name . "Interested in " . $course. " Number" . $phone . " " . " Wrote" . "\n\n" . $_POST['comment'];
$message2 = "Copy " . $name ."\n\n" . "Interested in:" . $course . "\n\n" . $_POST['comment'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$comment,$message,$headers);
mail($from,$comment2,$message2,$headers2);
// sends a copy of the message to the sender
header($thank_you);
// This redirects to page thanking for contact.
}
else
header($error);
// This redirects to page informing about failure.
$message = "couldn't verify Captcha. Email not sent.";
echo '<script type="text/javascript">mailNotSent();</script>';
}
?>
<section id="contact" class="contact">
<div class="container pseudonest">
<div class="pseudonest contact__head--nest">
<h1 class="display-5 lh-1 mb-2 contact__head--pseudocircle contact__head--header mx-auto">Enroll now</h1>
</div>
<div class="container m-auto">
<div class="d-flex justify-content-center contact__form">
<div class="col-md-7 col-lg-8">
<form action="" method="post">
<form class="needs-validation" novalidate>
<div class="row g-3">
<div class="col">
<label for="name" id="nameHeader" class="form-label">Name</label>
<input type="text" class="form-control radio__margin" id="name" name="name"
placeholder="" value="<?php echo $name;?>" required>
<div class="invalid-feedback">
<?php echo $nameErr;?>
</div>
<label for="email" class="form-label">Email</label></label>
<input type="email" class="form-control radio__margin" id="email" name="email"
placeholder="you#example.com" value="<?php echo $email;?>" required>
<div class="invalid-feedback">
<?php echo $emailErr;?>
</div>
<label for="phone" class="form-label">Phone</label></label>
<input type="number" class="form-control radio__margin" id="phone" name="phone"
pattern="[0-9]+" placeholder="+48 111 222 333" value="<?php echo $phone;?>">
<div class="invalid-feedback">
<?php echo $phoneErr;?>
</div>
</div>
<div class="col radio__col">
<label for="firstName" class="form-label">Course?</label>
<div class="row radio__section">
<label class="radio__container">English
<input type="radio" name="course"
<?php if (isset($course) && $course=="English") echo "checked";?>
value="English">
<span class="radio__checkmark"></span>
</label>
<label class="radio__container">
<input type="radio" name="course"
<?php if (isset($course) && $course=="Polish") echo "checked";?>
value="Polish">
<span class="radio__checkmark"></span>Polish
</label>
<label class="radio__container">
<input type="radio" name="course"
<?php if (isset($course) && $course=="Italian") echo "checked";?>
value="Italian">
<span class="radio__checkmark"></span>Italian
</label>
<span class="error"> <?php echo $courseErr;?></span>
</div>
</div>
</div>
<div class="col-12 mb-5">
<label for="email-content" class="form-label">Content</label>
<div class="input-group has-validation">
<textarea class="form-control" rows="5" name="comment"
cols="30"><?php echo $comment;?></textarea>
<div class="invalid-feedback">
</div>
</div>
</div>
<form id="frmContact" action="varify_captcha.php" method="POST" novalidate="novalidate">
<div class="g-recaptcha my-3" data-sitekey="mySiteKey">
</div>
<input type="submit" name="submit" value="Send" id="submit"
class="btn btn-primary contact__form--btn">
<div id="fakeSubmit" class="btn btn-primary contact__form--btn hidden">Fill the form
</div>
</form>
</form>
</div>
</div>
</section>

(PHP) contact us form message textarea missing [duplicate]

This question already has answers here:
(PHP) Stuck making submission form anti spam
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 3 years ago.
When I open the email the message is always empty, I get the name and email but message is empty,
I recently added google recaptcha v3 which was giant pain , but It is now working.
anyway I tried to debug this, and It show no errors, the message textarea send to email but I receive it empty...
this is the form
<?php
if(isset($_POST['submit'])){
$captcha=$_POST['token'];
$secret = 'censord';
$response = file_get_contents(
"https://www.google.com/recaptcha/api/siteverify?secret=" . $secret . "&response=" . $captcha . "&remoteip=" . $_SERVER['REMOTE_ADDR']
);
// use json_decode to extract json response
$response = json_decode($response);
if($response->success == true) {
//save data to database
echo '<div class="alert alert-success">
<strong>Success!</strong> Data is saved.
</div>';
} else {
echo '<div class="alert alert-warning">
<strong>warning!</strong> Failed to save data.
</div>';
}
}
?>
<style>
</style>
</head>
<body>
<?php
if(isset($_POST['submit'])){
$name = htmlspecialchars(stripslashes(trim($_POST['username'])));
$email = htmlspecialchars(stripslashes(trim($_POST['email'])));
$text = htmlspecialchars(stripslashes(trim($_POST['textt'])));
if(!preg_match("/^[A-Za-z .'-]+$/", $name)){
$name_error = 'Invalid name';
}
if(!preg_match("/^[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/", $email)){
$email_error = 'Invalid email';
}
if(strlen($text) === 0){
$message_error = 'Your message should not be empty';
}
if(preg_match('/http|www/i',$comments)) {
$error_message .= "We do not allow a url in the comment.<br />";
}
}
?>
<div id="container">
<div class="form-wrap">
<h1>Report bug</h1>
<p>Report us if you find any bug or broken link in our free online programming classes.</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<div class="form-group">
<label for="username">Name:</label>
<input type="text" name="username">
<p><?php if(isset($name_error)) echo $name_error; ?></p>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" name="email">
<p><?php if(isset($email_error)) echo $email_error; ?></p>
</div>
<div class="form-group">
<label for="textt">Message:</label>
<textarea type="text" name="textt" rows="22" cols="42"></textarea>
<p><?php if(isset($message_error)) echo $message_error; ?></p>
</div>
<button type="submit" name="submit" value="Submit" class="btn">Report us</button>
<input type="hidden" name="action" value="validate_captcha">
<?php
if(isset($_POST['submit']) && !isset($name_error) && !isset($subject_error) && !isset($email_error) && !isset($message_error)){
$to = 'censord'; // edit here
$body = " Name: $name\n E-mail: $email\n Message:\n $message";
if(mail($to, $subject, $body)){
echo '<p style="color: green">Message sent</p>';
}else{
echo '<p>Error occurred, please try again later</p>';
}
}
?>
</form>
</div>
</div>
</body>
<script>
grecaptcha.ready(function() {
grecaptcha.execute('censord', {action: 'validate_captcha'}).then(function(token) {
console.log(token);
document.getElementById("token").value = token;
});
});
</script>
</html>

Php javascript conflict in wordpress template file

I have built a contact form for my wordpress site. Four fields are there - name, email, subject, message. For logged in users I want their name and email to be auto-filled in their respective fields in the form and those name, email fields will be disabled for them to edit. And for non-logged in users they will put name, email fields manually. I have put this code in the page template file -
<?php
$current_user = wp_get_current_user();
$user_email = $current_user->user_email;
$user_name = $current_user->user_firstname.' '.$current_user>user_lastname;
if ( 0 != $current_user->ID ) {
echo '<script type="text/javascript">
document.getElementById("curUserName").value = "'.$user_name.'";
document.getElementById("curUserName").disabled = "disabled";
document.getElementById("curUserEmail").value = "'.$user_email.'";
document.getElementById("curUserEmail").disabled = "disabled";
</script>';
}
?>
But this code is disabling name, email fields for both users (logged in and non-logged in). I have controlled the script through if condition. Still the javascript is applying for both users. Please advise where I have gone wrong.
Here is the form html -
<form action="/success.php" method="post">
<label>Name :</label><br>
<input type="text" id="curUserName" name="sender_name" required><br>
<label>Email :</label><br>
<input type="text" id="curUserEmail" name="sender_email" required><br>
<label>Subject :</label><br>
<input type="text" name="sender_sub"><br>
<label>Message</label><br>
<textarea name="sender_msg" rows="4" cols="60" required></textarea><br>
<input type="submit" name="submit" value="Send">
</form>
The source you are going to change has disabled option already.. so just remove it if the user is not logged in :)
<?php
$current_user = wp_get_current_user();
$user_email = $current_user->user_email;
$user_name = $current_user->user_firstname.' '.$current_user>user_lastname;
echo '<script type="text/javascript">';
if ( 0 != $current_user->ID )
{
echo 'document.getElementById("curUserName").value = "'.$user_name.'"
document.getElementById("curUserName").disabled = "disabled"
document.getElementById("curUserEmail").value = "'.$user_email.'"
document.getElementById("curUserEmail").disabled = "disabled"';
}
else
{
echo 'document.getElementById("curUserName").disabled = false;
document.getElementById("curUserEmail").disabled = false;';
}
echo '</script>';
?>
Don't echo javascript with php. It's bad practice.
Try using value tags in your inputs, check if user logged in with a ternary operator, and if so, echo to value tag their credentials.
<?php (is_user_logged_in()) ? $current_user = wp_get_current_user() : $current_user = false; ?>
<label>Name</label>
<input type="text" id="curUserName" name="sender_name" value="<?php ($current_user) ? echo $current_user->user_name : '' ?>" required>
<label>Email</label>
<input type="text" id="curUserEmail" name="sender_email" value="<?php ($current_user) ? echo $current_user->user_email : '' ?>" required>

checked term and condition before submit form

if user want to submit their form, they have to checked the terma and condition box first.
so where should i add the code?
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Page Title Goes Here</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="form1.css"/>
</head>
<body onload="disableSubmit()">
<?php
//define variable and set to empty value
$forenameErr = $surnameErr = $emailErr = $postalAddressErr = $landLineTelNoErr = $mobileTelNoErr = $sendMethodErr = "";
$valid = true;
// if forename is null , make it null , else test_input()
$forename = empty($_POST["forename"]) ? NULL : test_input($_POST["forename"]);
// if surname is null , make it null , else test_input()
$surname = empty($_POST["surname"]) ? NULL : test_input($_POST["surname"]);
// if postalAddress is null , make it null , else test_input()
$postalAddress = empty($_POST["postalAddress"]) ? NULL : test_input($_POST["postalAddress"]);
// if landLineTelNo is null , make it null , else test_input()
$landLineTelNo = empty($_POST["landLineTelNo"]) ? NULL : test_input($_POST["landLineTelNo"]);
// if mobileTelNo is null , make it null , else test_input()
$mobileTelNo = empty($_POST["mobileTelNo"]) ? NULL : test_input($_POST["mobileTelNo"]);
//email
$email = empty($_POST["email"]) ? NULL : test_input($_POST["email"]);
// if sendMethod is null , make it null , else test_input()
$sendMethod = empty($_POST["sendMethod"]) ? NULL : test_input($_POST["sendMethod"]);
if (isset($_POST["submit"])){
//check forename
if($forename === NULL) {
//forename is empty
$forenameErr = "*Forename is required";
$valid = false;
} else {
//check characters
if (!preg_match("/^[a-zA-Z ]*$/",$forename)) {
$forenameErr = "Only letters and white space allowed";
$valid = false;
}
}
//check surname
if($surname === NULL){
//surname is empty
$surnameErr = "*Surname is required";
$valid = false; //false
} else {
//check charaters
if (!preg_match("/^[a-zA-Z ]*$/",$surname)) {
$surnameErr = "*Only letters and white space allowed";
$valid = false;
}
}
//check address
if (!preg_match("/^[a-zA-Z0-9\-\\,. ]*$/", $postalAddress)) {
// check characters
$postalAddressErr = "*Invalid Postal Address";
$valid = false;//false
}
// check if invalid telephone number added
if (!preg_match("/^$|^[0-9]{12}$/",$landLineTelNo)) {
//check number
$landLineTelNoErr = "*Only 12 digit number can be entered";
$valid = false;//false
}
//check valid mobiel tel no
if (!preg_match("/^$|^[0-9]{11}$/",$mobileTelNo)) {
//check number
$mobileTelNoErr = "*Only 11 digit number can be entered";
$valid = false;//false
}
//check valid email
if (isset($email) && !filter_var($email, FILTER_VALIDATE_EMAIL))
{ $emailErr = "*Invalid email format";
$valid = false;//false
}
//check sendMethod
if($sendMethod === NULL){
//send method is empty
$sendMethodErr = "*Contact method is required";
$valid = false; //false
} else {
$sendMethod = test_input($_POST["sendMethod"]);
}
//sendmethod link to information filled
if (isset($sendMethod) && $sendMethod=="email" && $email ==NULL){
$emailErr ="*Email is required ";
$valid = false;
}
if (isset($sendMethod) && $sendMethod=="post" && $postalAddress ==NULL){
$postalAddressErr ="*Postal Address is required ";
$valid = false;
}
if (isset($sendMethod) && $sendMethod=="SMS" && $mobileTelNo ==NULL){
$mobileTelNoErr ="*Mobile number is required ";
$valid = false;
}
//if valid then redirect
if($valid){
$_SESSION['forename'] = $forename;
$_SESSION['surname'] = $surname;
$_SESSION['email'] = $email;
$_SESSION['postalAddress'] = $postalAddress;
$_SESSION['landLineTelNo'] = $landLineTelNo;
$_SESSION['mobileTelNo'] = $mobileTelNo;
$_SESSION['sendMethod'] = $sendMethod;
header('Location: userdetail.php');
exit();
}
} else{
//user did not submit form!
}
//check
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div id="wrapper">
<h1>Welcome to Chollerton Tearoom! </h1>
<nav>
<ul>
<li>Home</li>
<li>Find out more</li>
<li>Offer</li>
<li>Credit</li>
<li>Admin</li>
<li>WireFrame</li>
</ul>
</nav>
<form id = "userdetail" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<fieldset id="aboutyou">
<legend id="legendauto">user information</legend>
<p>
<label for="forename">Forename: </label>
<input type="text" name="forename" id="forename" value="<?php echo $forename;?>">
<span class="error"> <?php echo $forenameErr;?></span>
</p>
<p>
<label for="surname">Surname:</label>
<input type="text" name="surname" id="surname" value="<?php echo $surname;?>">
<span class="error"> <?php echo $surnameErr;?></span>
</p>
<p>
<label for="postalAddress">Postal Address:</label>
<input type="text" name="postalAddress" id="postalAddress" value="<?php echo $postalAddress;?>">
<span class="error"> <?php echo $postalAddressErr;?></span>
</p>
<p>
<label for="landLineTelNo">Landline Telephone Number:</label>
<input type="text" name="landLineTelNo" id="landLineTelNo" value="<?php echo $landLineTelNo;?>" >
<span class="error"> <?php echo $landLineTelNoErr;?></span>
</p>
<p>
<label for="mobileTelNo">Moblie:</label>
<input type="text" name="mobileTelNo" id="mobileTelNo" value="<?php echo $mobileTelNo;?>" >
<span class="error"> <?php echo $mobileTelNoErr;?></span>
</p>
<p>
<label for="email">E-mail:</label>
<input type="text" name="email" id="email" value="<?php echo $email;?>">
<span class="error"> </span> <?php echo $emailErr;?> </span>
</p>
<fieldset id="future">
<legend>Lastest news</legend>
<p>
Choose the method you recommanded to recevive the lastest information
</p>
<br>
<input type="radio" name="sendMethod" id="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="email") echo "checked";?> value="email">
Email
<input type="radio" name="sendMethod" id="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="post") echo "checked";?> value="post">
Post
<input type="radio" name="sendMethod" id="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="SMS") echo "checked";?> value="SMS">
SMS
<span class="error"> <?php echo $sendMethodErr;?></span>
</fieldset>
<p><span class="error">* required field.</span></p>
<input type="checkbox" name="terms" id="terms">
I have read and agree to the Terms and Conditions and Privacy Policy
<br><br>
<p>
<input type="submit" name="submit" value="submit" />
</p>
</form>
</form>
</fieldset>
</form>
</div>
</body>
</html>
and so here is my userdetail.php to get user data...
<?php
session_start();
$forename = $_SESSION['forename'];
$surname = $_SESSION['surname'];
$email = $_SESSION['email'];
$postalAddress = $_SESSION['postalAddress'];
$landLineTelNo = $_SESSION['landLineTelNo'];
$mobileTelNo = $_SESSION['mobileTelNo'];
$sendMethod = $_SESSION['sendMethod'];
echo "<h1>Successfull submission :</h1>";
echo "<p>Forename : $forename <p/>";
echo "<p>Surname : $surname <p/>";
if($_SESSION['postalAddress']==NULL)
{echo "<p>postalAddress:NULL</p>";}
else {echo "<p>PostalAddress : $postalAddress </p>";}
if($_SESSION['email']==NULL)
{echo "<p>email:NULL<p/>";}
else {echo "<p>email : $email</p>";}
if($_SESSION['landLineTelNo']==NULL)
{echo "<p>landLineTelNo:NULL<p/>";}
else {echo "<p>landLineTelNo : $landLineTelNo </p>";}
if($_SESSION['mobileTelNo']==NULL)
{echo "<p>mobileTelNo:NULL<p/>";}
else {echo "<p>mobileTelNo : $mobileTelNo </p>";}
echo "<p>sendMethod : $sendMethod </p>";
?>
i need the term and condition check box to be checked else use cannot submit the form....
REMEMBER! Using javascript will just make it easy for user.It prevents loading another page to display error. STILL if a browser has javascript turned of it will pass the checked Terms without even checking it. so you should Always check it serverside (PHP) and use javascript for users ease.
in your HTML:
<form id="userdetail" ....>
...
<input type="checkbox" name="terms" id="terms" value="accepted" />
...
</form>
then in your javascript:
Pure JS:
document.getElementById('userdetail').addEventListener('submit', function(event){
if(document.getElementById('terms').checked == false){
event.preventDefault();
alert("By signing up, you must accept our terms and conditions!");
return false;
}
});
Using JQuery (jquery.com)
$('#userdetail').submit(function(event){
if($('#terms').is(':checked') == false){
event.preventDefault();
alert("By signing up, you must accept our terms and conditions!");
return false;
}
});
and in your PHP to check if it is checked you should use
if(isset($_POST['terms']) && $_POST['terms'] == 'accepted') {
// Continue Registring
} else {
// Display Error
}
Instead of submit you do:
<input type="button" onclick="javascript:myFunction()" Value="Submit">
And then the javascript function:
function myFunction() {
if(document.getElementById("terms").checked == true){
document.getElementById("userdetail").submit();
}
else{
alert("You have to agree on terms and conditions");
}
}
In Jquery you can do like below:
<script>
$('#userdetail').submit(function(){
if($('#terms').is(':checked'))
{
return true;
}
else
{
return false;
}
});
</script>
Replace the part of html with the given html in answer and add the function below to you script...
function verify_terms()
{
if (!$('#terms').is(':checked'))
{
alert('Please agree terms and conditions');
return false;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="checkbox" name="terms" id="terms">
I have read and agree to the Terms and Conditions and Privacy Policy
<br><br>
<p>
<input type="submit" name="submit" onclick="return verify_terms();" value="submit" />

PHP loop with html forms and javascript submit button only submitting last form in loop

I have a PHP loop that displays multiple HTML forms. I have javascript onClick for the submit button. I am attempting to cause the submit button on each form to only submit the form it belongs to. My problem is after the loop displays several forms only the very last form displayed from the loop will submit. Any forms previous to the last form in the loop do not submit when the submit button is clicked. I did find some helpful information over at Post form in while loop with javascript submit and also at add onclick function to a submit button and these did help me in my attempt but they did not help me to solve this problem I ran into. Any suggestions would be greatly appreciated.
Here is the javascript in the head section:
<!-- Script to fire uploaded photos form bound to unique id -->
<script>
function submitForm(image_id) {
document.forms[image_id].submit();
return false;
}
</script>
<!-- End of script to fire uploaded photos form bound to unique id -->
Here is the PHP loop and form:
<div id="uploaded-photos">
<!-- Start of Uploaded Photos -->
<?php
// Selecting all images from the database
$select_images = "select * from files where email = '$_SESSION[email]'";
$run_images = mysqli_query($conn, $select_images);
while($row=mysqli_fetch_array($run_images)){
// Creating variables for post id, title, date, author, image, keywords and content
$image_name = $row['name'];
$image_description = $row['description'];
$image_title = $row['title'];
$image_directory_name = $row['image_directory_name'];
$image_keywords = $row['keywords'];
$image_privacy = $row['privacy'];
$image_id = $row['id'];
?>
<div id="uploaded-photos-individual">
<div id="uploaded_photos_image_wrapper">
<form method="post" name="<?php echo "$image_id"; ?>" action="nonadmin_user_profile.php">
<p class="av-radio2"><img src="../photo-uploads/server/php/files/<?php echo "$image_directory_name"; ?>/thumbnail/<?php echo "$image_name"; ?>" width="100" height="100" alt="<?php echo "$image_description"; ?>" title="<?php echo "$image_title"; ?>">
<br>
<input type="radio" value="<?php echo "$image_name"; ?>" name="uploaded-personal-avatar-name" <?php if ("$uploaded_personal_avatar_name" == "$image_name") {echo 'checked="checked"';} else {echo '';} ?>>Personal Profile
<br>
<input type="radio" value="<?php echo "$image_name"; ?>" name="uploaded-business-avatar-name" <?php if ("$uploaded_business_avatar_name" == "$image_name") {echo 'checked="checked"';} else {echo '';} ?>>Business Profile<input type="hidden" name="image-id" value="<?php echo "$image_id"; ?>"</p>
</div> <!-- End of Uploaded Photos IMG Wrapper -->
<div id="uploaded-photos-inputs">
<table style="width:100%">
<tr>
<td class="tdleft"><strong>Title:</strong></td>
<td align="left"><input type="text" name="image-title" style="width:99%" maxlength="250" value="<?php echo "$image_title"; ?>"></td>
</tr>
<tr>
<td class="tdleft"><strong>Description:</strong></td>
<td align="left"><input type="text" name="image-description" style="width:99%" maxlength="250" value="<?php echo "$image_description"; ?>"></td>
</tr>
<tr>
<td class="tdleft"><strong>Keywords:</strong></td>
<td align="left"><input type="text" name="image-keywords" style="width:99%" maxlength="250" value="<?php echo "$image_keywords"; ?>"></td>
</tr>
<tr>
<td class="tdleft"><strong>Name:</strong></td>
<td align="left"><input type="text" name="image-name" style="width:99%" maxlength="250" readonly="readonly" value="<?php echo "$image_name"; ?>"></td>
</tr>
<tr>
<td class="tdleft"><strong>Privacy:</strong></td>
<td align="left"><select name="image-privacy"><option value="Private" <?php if ("$image_privacy" == 'Private') {echo 'selected="'."$image_privacy".'"';} else {echo '';} ?>>Private</option><option value="Public" <?php if ("$image_privacy" == 'Public') {echo 'selected="'."$image_privacy".'"';} else {echo '';} ?>>Public</option>
</select></td>
</tr>
</table>
</div> <!-- End of Uploaded Photos Inputs -->
<div id="uploaded-photos-submit">
<input type="submit" value="Update This Photo" class="submit_button" name="<?php echo "$image_id"; ?>" <?php echo 'onClick="return submitForm($image_id);"'; ?>>
</div>
</form>
</div> <! -- End of Uploaded Photos Individual -->
<?php } ?>
Here is the code to accept the form submit and load the database:
<!-- Code for Uploaded Photos Update Form -->
<?php
if (isset($_POST["$image_id"])) {
// Let's sanitize the user's uploaded avatar selection for personal profile
$uploaded_personal_avatar_name_input = trim(((isset($conn) && is_object($conn)) ? mysqli_real_escape_string($conn, $_POST['uploaded-personal-avatar-name']) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : "")));
// Let's sanitize the user's uploaded avatar selection for business profile
$uploaded_business_avatar_name_input = trim(((isset($conn) && is_object($conn)) ? mysqli_real_escape_string($conn, $_POST['uploaded-business-avatar-name']) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : "")));
// Let's sanitize the user's uploaded image title
$image_title_input = trim(((isset($conn) && is_object($conn)) ? mysqli_real_escape_string($conn, $_POST['image-title']) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : "")));
// Let's sanitize the user's uploaded image description
$image_description_input = trim(((isset($conn) && is_object($conn)) ? mysqli_real_escape_string($conn, $_POST['image-description']) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : "")));
// Let's sanitize the user's uploaded image keywords
$image_keywords_input = trim(((isset($conn) && is_object($conn)) ? mysqli_real_escape_string($conn, $_POST['image-keywords']) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : "")));
// Let's sanitize the user's uploaded image privacy settings
$image_privacy_input = trim(((isset($conn) && is_object($conn)) ? mysqli_real_escape_string($conn, $_POST['image-privacy']) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : "")));
// Let's sanitize the user's uploaded image id
$image_id_input = trim(((isset($conn) && is_object($conn)) ? mysqli_real_escape_string($conn, $_POST['image-id']) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : "")));
if ('$uploaded_personal_avatar_name_input' == '') {}
else {
// Let's add all this stuff to the database if an uploaded user photo is selected for personal profile use
mysqli_query($conn, "UPDATE nonadmin_user_login SET
uploaded_personal_avatar_name='$uploaded_personal_avatar_name_input',
uploaded_personal_avatar_usage='1',
built_in_personal_avatar_name='',
built_in_personal_avatar_usage='0'
WHERE email = '$_SESSION[email]'") or die(((is_object($conn)) ? mysqli_error($conn) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)));
}
if ('$uploaded_business_avatar_name_input' == '') {}
else {
// Let's add all this stuff to the database if an uploaded user photo is selected for business profile use
mysqli_query($conn, "UPDATE nonadmin_user_login SET
uploaded_business_avatar_name='$uploaded_business_avatar_name_input',
uploaded_business_avatar_usage='1',
built_in_business_avatar_name='',
built_in_business_avatar_usage='0'
WHERE email = '$_SESSION[email]'") or die(((is_object($conn)) ? mysqli_error($conn) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)));
}
// Let's add some remaining stuff to the database regardless if any profile picture was selected
mysqli_query($conn, "UPDATE files SET
title='$image_title_input',
description='$image_description_input',
keywords='$image_keywords_input',
privacy='$image_privacy_input'
WHERE email = '$_SESSION[email]' AND id = '$image_id_input'") or die(((is_object($conn)) ? mysqli_error($conn) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)));
// If the database insert fails let's print a query failed warning
if (mysqli_affected_rows($conn) == 0) {
echo 'Something went wrong';
}
// If the database insert succeeded we can alert the user and refresh the page
else {
//echo " <script>alert('Photo Selection Update Successful!');</script> ";
echo "<script>window.location=window.location</script>";
//echo "<script>$(window).load(function() { alert('Photo Selection Update Successful!'); });</script>";
}
}
?>
<!-- End of Code for Uploaded Photos -->
I solved this problem. The issue here is using the same variable name for the name of the form and the name of the submit button. Apparently this created confusion on submit since the form name and the submit button name were both coded as $image_id.
Previous code that didn't work:
<input type="submit" value="Update This Photo" class="submit_button" name="<?php echo "$image_id"; ?>" <?php echo 'onClick="return submitForm($image_id);"'; ?>>
<form method="post" name="<?php echo "$image_id"; ?>" action="nonadmin_user_profile.php">
By simply changing the name of the submit button everything works and the corrected code is shown below:
<input type="submit" value="Update This Photo" class="submit_button" name="upload-photo-form" <?php echo 'onClick="return submitForm($image_id);"'; ?>>
<form method="post" name="<?php echo "$image_id"; ?>" action="nonadmin_user_profile.php">

Categories