Switching over from C# to PHP for a bit and not seeing what I am doing wrong here.
What I am wanting to to is when I click the submit button - I want the email sent (like it is doing) but then I want the input text fields to clear out the old text the user had previously input.
The one way I had it figured out would clear my test before it was actually submitted, which didn't help me very much.
Any input on how to do this?
<?php
/*
* Template Name: Contact
* Description: Contact Us
*/
get_header();
?>
<div class="container">
<div class="section group">
<div class="col span_2_of_2">
<h1> Contact Us <h1>
<p style="font-size:16px"> Radiology Services LLC is located on the east side of Evansville, IN off the Robert D. Orr Highway.</p>
<iframe src="https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d3146.027108890167!2d- 87.45272299999999!3d37.953153!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x0%3A0x170f5925d75e6135!2s Radiology+Services+LLC!5e0!3m2!1sen!2sus!4v1404175203674" width="100%" height="350px" frameborder="0" style="border:0"></iframe>
</div>
<div class="col span_1_of_2" style="padding-left:40px;>
<?php
//response generation function
$response = "";
//function to generate response
function my_contact_form_generate_response($type, $message){
global $response;
if($type == "success") $response = "<div class='success'>{$message}</div>";
else $response = "<div class='error'>{$message}</div>";
}
//response messages
$not_human = "Human verification incorrect.";
$missing_content = "Please supply all information.";
$email_invalid = "Email Address Invalid.";
$message_unsent = "Message was not sent. Try Again.";
$message_sent = "Thanks! Your message has been sent.";
//user posted variables
$name = $_POST['message_name'];
$email = $_POST['message_email'];
$message = $_POST['message_text'];
$human = $_POST['message_human'];
//php mailer variables
$to = 'aje#gmail.com';
$subject = "Someone sent a message from ".get_bloginfo('name');
$headers = 'From: '. $email . "\r\n" .
'Reply-To: ' . $email . "\r\n";
if(!$human == 0){
if($human != 2) my_contact_form_generate_response("error", $not_human); //not human!
else {
//validate email
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
my_contact_form_generate_response("error", $email_invalid);
else //email is valid
{
//validate presence of name and message
if(empty($name) || empty($message)){
my_contact_form_generate_response("error", $missing_content);
}
else //ready to go!
{
$sent = wp_mail($to, $subject, strip_tags($message), $headers);
if($sent) my_contact_form_generate_response("success", $message_sent);
else my_contact_form_generate_response("error", $message_unsent);
}
}
}
}
else if ($_POST['submitted']) my_contact_form_generate_response("error", $missing_content);
?>
<?php while ( have_posts() ) : the_post(); ?>
<div class="entry-content">
<?php the_content(); ?>
<style type="text/css">
.error{
padding: 5px 9px;
border: 1px solid red;
color: red;
border-radius: 3px;
}
.success{
padding: 5px 9px;
border: 1px solid green;
color: green;
border-radius: 3px;
}
form span{
color: red;
}
.subBtn{
width:100%;
border-radius: 0px;
background-color:#5bb75b;
color:#FFFFFF;
}
.subBtn:hover{
background-color:#408140;
}
.m{
width:100%;
border-radius: 0px;
}
</style>
<script language="javascript">
fromreset()
{
myform.reset();
document.myform.[textbox Id] = " ";
}
</script>
<form name="myform" id="myform"action="<?php the_permalink(); ?>" method="post">
<label for="name" class="m">Name: <span>*</span> <br>
<input type="text" class="m" id="name" name="message_name" value="<?php echo esc_attr($_POST['message_name']); ?>">
</label>
<label for="message_email" class="m">Email: <span>*</span> <br>
<input type="text" class="m" id="email" name="message_email" value="<?php echo esc_attr($_POST['message_email']); ?>">
</label>
<label for="message_text" class="m" id="mu">Message: <span>*</span> <br>
<textarea type="text" class="m" id="textm" name="message_text"><?php echo esc_textarea($_POST['message_text']); ?></textarea>
</label>
<label for="message_human" class="m">Human Verification: <span>*</span> <br>
<input type="text" class="m" name="message_human"> + 3 = 5
</label>
<input type="hidden" name="submitted" value="1" class="m">
<input type="hidden" name="submitted" value="1" style="width:100%">
<input type="submit" value="submit" class="subBtn" onclick="formreset();">
<?php echo $response; ?>
</form>
</div>
</div>
<?php endwhile; // end of the loop. ?>
</div><!-- #content -->
</div>
<?php get_footer(); ?>
Related
If I enter an Incorrect email address or password my site refreshes to the top of the page and I see this error
Incorrect email and Pass
I have to scroll back down to where my form is to see a detailed error.
I want to prevent my page going to the top.
I have searched for a solution on here but can't find anything.
HTML Code:
<body>
<form method="post" style="margin-right:450px;">
<table align="center" cellspacing="3px;">
<tr>
<td>
<input style="border:1px #666 solid; border-radius: 4px; width: 180px; padding: 12px 20px; font-size:18px;" type="email" name="mail" required placeholder="Your Email">
</td>
<td>
<input style="border:1px #666 solid; border-radius: 4px; width: 180px; padding: 12px 20px; font-size:18px;" type="password" name="pass" required placeholder="Your Password">
</td>
</tr>
</table>
<br><br>
<button class="button button3" type="submit" name="log" style="color:#FFF; text-align:center; margin-left:70px;">Log In</button></td>
</form>
</body>
PHP Code:
<?php
$con=mysqli_connect("localhost","root","","form_data");
if(isset($_POST['log']))
{
$_SESSION['mail'] = $_POST['mail'];
$email = $_POST['mail'];
$Password = $_POST['pass'];
$query = mysqli_query($con,"select * from registration where (User_name = '$email' or Email= '$email') and Password = '$Password' ");
$check = mysqli_num_rows($query);
if($check == 1)
{
echo "<h1> User Login <h1>";
header("location:exam.php");
}
else
{
echo "<div class='error'> ";
echo "!! Invalid Username Or Password !!";
echo "</div>";
}
}
?>
I want to make input fields red on validation errors in code-igniter with ajax and jquery but it makes all input fields red even if only one field have error in it. I want to make that particular input field red which have error in it.
This is my form code:
<?php echo form_open(); ?>
<div class="form-group">
<input name="email" type="text" id="email" class="form-control" placeholder="Email" />
</div>
<div class="form-group">
<?php echo form_password(array(
'name'=>'password',
'id'=> 'password',
'placeholder'=>'Password',
'class'=>'form-control',
'value'=> set_value('password'))); ?>
</div>
<div id="message" style="color:red;"></div>
<div class="checkbox pull-left">
<label>
<input type="checkbox"> Remember Me
</label>
</div>
<button name="submit" id="formsubmitbutton" type="submit" class="btn btn-lg btn-primary btn-block">Signin</button>
<?php echo form_close(); ?>
<div class="modal-footer">
<div class="col-md-12">
<p style="color:#aeaeae; text-align:center;">Help, I forgot my login details.</p>
</div>
</div>
</div>
<div class="tab-pane fade" id="signup">
<h3 class="text-center"><i class="fa fa-lock"></i> Create User Account</h3>
<?php echo form_open();?>
<div class="form-group">
<input class="form-control" id="fname" name="fname" placeholder="Your First Name" type="text" value="<?php echo set_value('fname'); ?>" />
<span class="text-danger"><?php echo form_error('fname'); ?></span>
</div>
<div class="form-group">
<input class="form-control" id="lname" name="lname" placeholder="Last Name" type="text" value="<?php echo set_value('lname'); ?>" />
<span class="text-danger"><?php echo form_error('lname'); ?></span>
</div>
<div class="form-group">
<input class="form-control" id="emaill" name="emaill" placeholder="Email-ID" type="email" value="<?php echo set_value('emaill'); ?>" />
<span class="text-danger"><?php echo form_error('emaill'); ?></span>
</div>
<center><div class="form-group" style="width:100%;">
<select name="location" id="location" class="form-control">
<option >Location</option>
<option>Australia</option>
<option >Spain</option>
<option>UK</option>
</select>
</div></center>
<center><div class="form-group" style="width:100%;">
<select class="form-control" name="gender" id="gender" >
<option>Select one option:</option>
<option>Male</option>
<option>Female</option>
</select>
</div></center>
<center> <div class="form-group row-fluid" style="width:100%;">
<div class="col-xs-3">
<input type="text" name="phonee" class="form-control" id="ph" onkeypress="return isPhoneKey(event)" placeholder="+">
</div>
<div class="col-xs-9">
<input type="text"name="mobile" id="mobile" onkeypress="return isNumberKey(event)" class="form-control" >
</div>
</div></center>
<div class="form-group">
<input class="form-control" id="passwordd" name="passwordd" placeholder="Password" type="password" />
<span class="text-danger"><?php echo form_error('passwordd'); ?></span>
</div>
<div class="form-group">
<input class="form-control" id="cpassword" name="cpassword" placeholder="Confirm Password" type="password" />
<span class="text-danger"><?php echo form_error('cpassword'); ?></span>
</div>
<div class="form-group">
<input class="btn btn-default" id="submit" name="submit" type="button" value="Sign Up" style="width:90% ;height:42px; font-weight: normal; text-align:center; color:#fff; background-color:#286090; border-color:#204d74; border-radius:5px;" />
</div>
</br>
<div id="alert-msg"></div>
<?php echo form_close(); ?>
And this is my ajax jquery which makes the field red:
<script type="text/javascript">
jQuery('#submit').click(function() {
var form_data = {
fname: jQuery('#fname').val(),
lname: jQuery('#lname').val(),
email: jQuery('#emaill').val(),
pass: jQuery('#passwordd').val(),
repass: jQuery('#cpassword').val(),
location: jQuery('#location').val(),
mobile: jQuery('#mobile').val(),
gender: jQuery('#gender').val()
};
jQuery.ajax({
url: "<?php echo site_url('modal_contact/submit'); ?>",
type: 'POST',
data: form_data,
success: function(msg) {
if (msg == 'YES')
jQuery('#alert-msg').html('<div class="alert alert-success text-center">Your mail has been sent successfully!</div>');
else if (msg == 'NO')
jQuery('#alert-msg').html('<div class="alert alert-danger text-center">Error in sending your message! Please try again later.</div>');
else
jQuery('#alert-msg').html('<div class="alert alert-danger">' + msg + '</div>');
console.log('msg');
jQuery('#fname').attr('style', "border-radius: 5px; border:#FF0000 1px solid;");
jQuery('#lname').attr('style', "border-radius: 5px; border:#FF0000 1px solid;");
jQuery('#emaill').attr('style', "border-radius: 5px; border:#FF0000 1px solid;");
jQuery('#location').attr('style', "border-radius: 5px; border:#FF0000 1px solid;");
jQuery('#gender').attr('style', "border-radius: 5px; border:#FF0000 1px solid;");
jQuery('#mobile').attr('style', "border-radius: 5px; border:#FF0000 1px solid;");
jQuery('#ph').attr('style', "border-radius: 5px; border:#FF0000 1px solid;");
jQuery('#passwordd').attr('style', "border-radius: 5px; border:#FF0000 1px solid;");
jQuery('#cpassword').attr('style', "border-radius: 5px; border:#FF0000 1px solid;");
}
});
return false;
});
</script>
And this is my controller where it checks the validation and echos the validation_errors();
modal_contact controller:
<?php
class modal_contact extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper(array('form','url'));
$this->load->library(array('form_validation', 'email'));
$this->load->database();
$this->load->model('user_model');
}
function index()
{
$this->load->view('public/index.php');
}
function submit()
{
//set validation rules
$this->form_validation->set_rules('fname', 'First Name', 'trim|required|xss_clean|callback_alpha_space_only');
$this->form_validation->set_rules('lname', 'Last Name', 'trim|required|xss_clean|callback_alpha_space_only');
$this->form_validation->set_rules('email', 'Email ID', 'trim|required|valid_email|is_unique[user.email]');
$this->form_validation->set_rules('pass', 'Password', 'trim|required');
$this->form_validation->set_rules('repass', 'Re Password', 'trim|required|matches[pass]');
//run validation check
if ($this->form_validation->run() == FALSE)
{ //validation fails
echo validation_errors();
}
else
{
//insert the user registration details into database
$data = array(
'fname' => $this->input->post('fname'),
'lname' => $this->input->post('lname'),
'email' => $this->input->post('email'),
'password' => $this->input->post('pass'),
'location' => $this->input->post('location'),
'mobile' => $this->input->post('mobile'),
'gender' => $this->input->post('gender')
);
// insert form data into database
if ($this->user_model->insertUser($data))
{
// send email
if ($this->user_model->sendEmail($this->input->post('email')) )
{
echo "Your Mail has been sent successfully! Verify your account.";
}
else
{
echo "Error in sending your message! Please try again later.";
}
}
else
{
echo "Error";
}
}
}
function verify($hash=NULL)
{
if ($this->user_model->verifyEmailID($hash))
{
$this->session->set_flashdata('verify_msg','<div class="alert alert-success text-center">Your Email Address is successfully verified! Please login to access your account!</div>');
redirect('modal_contact/index');
}
else
{
$this->session->set_flashdata('verify_msg','<div class="alert alert-danger text-center">Sorry! There is error verifying your Email Address!</div>');
redirect('modal_contact/index');
}
}
//custom validation function to accept alphabets and space
function alpha_space_only($str)
{
if (!preg_match("/^[a-zA-Z ]+$/",$str))
{
$this->form_validation->set_message('alpha_space_only', 'The %s field must contain only alphabets and space');
return FALSE;
}
else
{
return TRUE;
}
}
}
?>
Thanks in advance!!
1st change all input field ID same as post key from ajax and submit function
for ex.
pass: jQuery('#passwordd').val(),
to
//in ajax
passwordd: jQuery('#passwordd').val(),//must be same
//in submit()
$this->form_validation->set_rules('pass', 'Password', 'trim|required');
put inside the top of submit() for set page header type json
$this->output->set_content_type('application/json');
and replace all following code
form
//run validation check
if ($this->form_validation->run() == FALSE)
{ //validation fails
echo validation_errors();
}
to
//run validation check
if ($this->form_validation->run() == FALSE)
{ //validation fails
$errors=$this->form_validation->error_array();
$this->output->set_output(json_encode(array('errors' => $errors)));
}
And
// insert form data into database
if ($this->user_model->insertUser($data))
{
........
.......
}else{
echo "Error";
}
to
// insert form data into database
if ($this->user_model->insertUser($data))
{
// send email
if ($this->user_model->sendEmail($this->input->post('email')) ){
$this->output->set_output(json_encode(
array(
'sendmail' => true,
'msg'=>"Your Mail has been sent successfully! Verify your account."
)
));
}else{
$this->output->set_output(json_encode(
array(
'sendmail' => false,
'msg'=>"Error in sending your message! Please try again later."
)
));
}
}else{
$this->output->set_output(json_encode(array('msg'=>"Error")));
}
and change all success callback function of ajax to
success: function(data) {
console.log(data);
if (data.sendmail){
jQuery('#alert-msg').html('<div class="alert alert-success text-center">'+data.msg+'</div>');
}else{
jQuery('#alert-msg').html('<div class="alert alert-danger text-center">'+data.msg+'</div>');
}
if(data.errors){
jQuery.each(data.errors,function(key,value){
jQuery('#'+key).attr('style', "border-radius: 5px; border:#FF0000 1px solid;");
});
}
}
Note:- if get any error please ask in comments
I have a self posting document that has form fields to fill out with php processing on the same document. My problem is that upon opening the page (website), the message "Message Sent!" shows up immediately before the form can be filled out with information. The php mail() function is linked to my email account so I get the form data email. But no data is sent because the email was sent before the form could be filled out. I want to be able to fill out the form before the email is sent off so that way the form sends actual information. Ive researced this topic and came up with nothing. Any help would be awesome! Here's my code...
<?php
foreach($_POST as $key => $value) //This will loop through each name-value in the $_POST array
{
$tableBody .= "<tr>"; //formats beginning of the row
$tableBody .= "<td>$key</td>"; //dsiplay the name of the name-value pair from the form
$tableBody .= "<td>$value</td>"; //dispaly the value of the name-value pair from the form
$tableBody .= "</tr>"; //End this row
}
echo "<table border='1'>";
echo "<tr><th>Field Name</th><th>Value of field</th></tr>";
foreach($_POST as $key => $value)
{
echo '<tr class=colorRow>';
echo '<td>',$key,'</td>';
echo '<td>',$value,'</td>';
echo "</tr>";
}
echo "</table>";
echo "<p> </p>";
?>
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>
body {
background-image: url("rbGrid.png");
background-size: 150%;
background-repeat: no-repeat;
text-align: center;
}
div {
background-color: black;
opacity: 0.9;
color: white;
text-align: center;
}
h1 {
color: white;
}
h2 {
color: white;
}
#borderStyle {
border: double thick red;
border-radius: 45px;
width: 50%;
margin: 0 auto;
}
#hiddenStuff {
display: none;
}
textarea {
display: none;
margin: 0 auto;
}
#mailingInformation {
display: none;
margin: 0 auto;
}
table {
margin: 0 auto;
border: solid thick red;
border-radius: 20px;
}
th {
border: solid thick red;
border-radius: 45px;
}
tr {
color: white;
border: solid thin red;
border-radius: 45px;
}
td {
color: white;
border: solid thin red;
border-radius: 45px;
}
</style>
<script>
function showProductProblemComments()
{
document.getElementById("textarea").style.display = "block";
}
function showMailingListForm()
{
document.getElementById("mailingInformation").style.display = "block";
}
</script>
</head>
<body>
<?php
$toEmail = "robinjennings#nephilim42.com"; //CHANGE within the quotes. Place email address where you wish to send the form data.
//Use your DMACC email address for testing.
$subject = "WDV341 Email Example"; //CHANGE within the quotes. Place your own message. For the assignment use "WDV101 Email Example"
$fromEmail = "robinjennings#nephilim42.com"; //CHANGE within the quotes. Use your DMACC email address for testing OR
//use your domain email address if you have Heartland-Webhosting as your provider.
// DO NOT CHANGE THE FOLLOWING LINES //
$emailBody = "Form Data\n\n "; //stores the content of the email
foreach($_POST as $key => $value) //Reads through all the name-value pairs. $key: field name $value: value from the form
{
$emailBody.= $key."=".$value."\n"; //Adds the name value pairs to the body of the email, each one on their own line
}
$headers = "From: $fromEmail" . "\r\n"; //Creates the From header with the appropriate address
if (mail($toEmail,$subject,$emailBody,$headers)) //puts pieces together and sends the email to your hosting account's smtp (email) server
{
echo("<p>Message successfully sent!</p>");
}
else
{
echo("<p>Message delivery failed...</p>");
}
/*$inName = $_POST["Name"];
$inEmail = $_POST["Email Address"];
$inAddress = $_POST["address"];
$inReason = $_POST["Reason"];
$inComments = $_POST["comments"];
$inMailBox = $_POST["Mailing List"];
$inUseAddress = $_POST["checkForAddress"];
$inFirstName = $_POST["mailingName"];
$inLastName = $_POST["mailingLastName"];
//$inMailingAdd $_POST["mailingAddress"];
$inPhoneNumber = $_POST["phoneNumber"];
$inMoreInfo = $_POST["More Info"];*/
?>
<h1>WDV341 Intro PHP</h1>
<h2>Programming Project - Contact Form</h2>
<div>
<form name="form1" method="POST" action="contactForm2.php">
<p> </p>
<p>
<div id = "borderStyle">
<label>Your Name:
<input type="text" name="Name" id="textfield" required>
</p>
<br><br>
<p>Your Email:
<input type="text" name="Email Address" id="textfield2" required>
</p>
<br><br>
<p>Your Address:
<input type = "text" name = "address" id = "living">
</p>
<br><br>
<p>Reason for contact:
<select name="Reason" id="select2" onChange = "showProductProblemComments()" required>
<option value="default">Please Select a Reason</option>
<option value="product">Product Problem</option>
<option value="return">Return a Product</option>
<option value="billing">Billing Question</option>
<option value="technical">Report a Website Problem</option>
<option value="other">Other</option>
</select>
</p>
<br><br>
<p>Comments:
<textarea name="comments" id="textarea" cols="45" rows="5"required></textarea>
</p>
<br><br>
<p>
<input type="checkbox" name="Mailing List" id="checkbox" onClick = "showMailingListForm()">
Please put me on your mailing list.
</p>
<div id = "mailingInformation">
<h3>Please fill out the form below to be put on the mailing list to recieve coupons and special offers</h3>
<p>Check the box to use address above
<input type = "checkbox" name = "checkForAddress" id = "checkAddress">
</p>
<p>First Name:
<input type = "text" name = "mailingName" id = "mailing">
</p>
<p>Last Name:
<input type = "text" name = "mailingLastName" id = "mailingLast">
</p>
<p>Mailing Address:
<input type = "text" name = "mailingAddress" id = "mailingAdd">
</p>
<p>Phone Number(Optional)
<input type = "text" name = "phoneNumber" id = "phone">
</p>
</div>
<p>
<input type="checkbox" name="More Info" id="checkbox2">
Send me more information about your products.</label>
</p>
<br><br>
<p>
<input type="hidden" name="hiddenField" id="hidden" value="application-id:US447">
</p>
<br><br>
<p>
<input type="submit" name="button" id="button" value="Submit">
<input type="reset" name="button2" id="button2" value="Reset">
</p>
<div>
</form>
<div id = "hiddenStuff">
<p>
<table border='a'>
<tr>
<th>Field Name</th>
<th>Value of Field</th>
</tr>
<?php echo $tableBody; ?>
</table>
<!--</p>
<p>Name: <?php echo $inName; ?></p>
<p>Email: <?php echo $inEmail; ?></p>
<p>Address: <?php echo $inAddress; ?></p>
<p>Reason: <?php echo $inReason; ?></p>
<p>Comments: <?php echo $inComments; ?></p>
<p>Mailing List: <?php echo $inMailBox; ?></p>
<p>Use Previous Address Given: <?php echo $inUseAddress; ?></p>
<p>First Name: <?php echo $inFirstName; ?></p>
<p>Last Name?: <?php echo $inLastName; ?></p>
<p>Mailing Address: <?php echo $inMailingAdd; ?></p>
<p>Phone Number: <?php echo $inPhoneNumber; ?></p>
<p>More Information: <?php echo $inMoreInfo; ?></p>-->
</div>
</body>
</html>
Some line of code have been commented out for the sake of experimenting. Thank you in for the help.
That's because of this:
<?php
$toEmail = "robinjennings#nephilim42.com"; //CHANGE within the quotes. Place email address where you wish to send the form data.
//Use your DMACC email address for testing.
//Example: $toEmail = "jhgullion#dmacc.edu";
$subject = "WDV341 Email Example"; //CHANGE within the quotes. Place your own message. For the assignment use "WDV101 Email Example"
$fromEmail = "robinjennings#nephilim42.com"; //CHANGE within the quotes. Use your DMACC email address for testing OR
//use your domain email address if you have Heartland-Webhosting as your provider.
//Example: $fromEmail = "contact#jhgullion.org";
// DO NOT CHANGE THE FOLLOWING LINES //
$emailBody = "Form Data\n\n "; //stores the content of the email
foreach($_POST as $key => $value) //Reads through all the name-value pairs. $key: field name $value: value from the form
{
$emailBody.= $key."=".$value."\n"; //Adds the name value pairs to the body of the email, each one on their own line
}
$headers = "From: $fromEmail" . "\r\n"; //Creates the From header with the appropriate address
if (mail($toEmail,$subject,$emailBody,$headers)) //puts pieces together and sends the email to your hosting account's smtp (email) server
{
echo("<p>Message successfully sent!</p>");
}
else
{
echo("<p>Message delivery failed...</p>");
}
?>
You have to check if your form is submitted then the above code executes. So put the above code in:
if( isset($_REQUEST['form_element_index']) )
{
// Above code here
// Now the code executes when form is submitted
}
Its happening because you have't created a form and asked user to give input.What you have to do is create a form and then retreive the form values and upon submitting the form send the mail.It would definitely work....
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
i want to validate my form using javascript .before the form submission,i want the server to display the error (if any)below the field input..how can i do dis in this code using external javascript file??
Here is my code:
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
.label_text {
float: left;
width: 44%;
text-align:right;
font-weight:bold;
color:purple;
}
.register1{
text-align:center;}
.header_tag{text-align:center;
font-weight:bold;
color:green;}
.header_tag1{ margin:10px;
float:left;
text-align:center;
font-weight:bold;
color:green}
.register_section{border:1px solid black;
text-align:center;
padding:20px;
margin-left:30%;
margin-right:30%;
float:none;
height:350px;
}
.input{ text-align:left;
float:left;
border:2px solid black;
}
.gender{float:left;}
.register{ float:left;
text-align:center;
color:green;
font-weight:bold;
padding:10px;
margin-left:36%;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $passwordErr = $password2Err = $emailErr = $genderErr = "";
$name = $password = $confirmpassword = $email = $gender = $description = "";
$result="";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = "";
$password = "";
$hostname = "";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with
$selected = mysql_select_db("test",$dbhandle)
or die("Could not select test");
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["password"])) {
$passwordErr = "Password is required";
} else {
$password = test_input($_POST["password"]);
}
if (empty($_POST["confirmpassword"])) {
$password2Err = "Confirm Password";
} else {
$password = test_input($_POST["confirmpassword"]);
}
if ($_POST['password']!= $_POST['confirmpassword'])
{
echo("Oops! Password did not match! Try again. ");
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["description"])) {
$comment = "";
} else {
$comment = test_input($_POST["description"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
if (empty($genderErr))
{if (empty($emailErr)){
if (empty($password2Err)){
if (empty($passwordErr)){
if (empty($nameErr)){
$result=mysql_query("SELECT * FROM person WHERE username ='$name' AND password='$password'AND Email='$email'");
if (mysql_num_rows($result)==0 )
{ // IF no previous user is using this username.
$result1=mysql_query("INSERT INTO person(username,password,Email,Gender) VALUES ( '$name', '$password','$email','$gender')");
{ if($result1)
////If the Insert Query was successfull.
// Send an email
// Finish the page:
{
echo '<div class="success">Thank you for registering! A confirmation email has been sent to ' . $email . ' </div>';
}
else
{ // If it did not run OK.
echo '<div class="errormsgbox">You could not be registered due to a system error. We apologize for any inconvenience.</div>';
}
}
}
// The username is not available.
else
{ echo '<div class="errormsgbox" >That username has already been registered.</div>';
}
}
}
}
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div class="register1">
<h2 class="header_tag">REGISTER HERE</h2>
<p><span class="error"></span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="register_section">
<div class="label_text">
Name:<span class="error">* </div>
<div class="input">
<input type="text" name="name"><br> </div>
<span class="error"><?php echo $nameErr;?></span>
<br><br>
<div class="label_text">
Password:<span class="error">* </div>
<div class="input">
<input type="text" name="password"><br> </div>
<span class="error"><?php echo $passwordErr;?></span>
<br><br>
<div class="label_text">
Confirm Password:<span class="error">* </div>
<div class="input">
<input type="text" name="confirmpassword"><br> </div>
<span class="error"><?php echo $password2Err;?></span>
<br><br>
<div class="label_text">
E-mail:<span class="error">* </div>
<div class="input">
<input type="text" name="email"><br></div>
<span class="error"><?php echo $emailErr;?></span>
<br><br>
<div class="label_text">
Description: </div>
<div class="input">
<textarea name="description" rows="5" cols="22"></textarea> </div>
<br><br>
<div class="label_text">
Gender:<span class="error">* </div>
<div class="gender">
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
</div>
<span class="error"><?php echo $genderErr;?></span>
<br><br><br>
<div class="register">
<input type="submit" name="submit" value="REGISTER">
<br>
<h3 class="header_tag1">"Back to Login
</div>
</div>
</div>
</form>
</body>
</html>
What you are trying to do is properly called client-side validation.
The easiest way to do this would be to use a third-party library, such as FormValidation.
For example, to validate your email field, you could do something like:
<form method="post" id="register_user" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
...
<input type="text" name="email" data-fv-emailaddress="true" data-fv-emailaddress-message="The value is not a valid email address" />
...
</form>
<script>
$('#register_user').submit(function() {
$('#register_user').formValidation();
});
</script>
Of course, you'll need to make sure to include the necessary CSS and JS libraries for jQuery, FormValidation, and a suitable content framework (such as Bootstrap).
For the record, if you're just looking for a basic user management script, I would strongly suggest that you avoid reinventing the wheel. Take an existing script, for example UserFrosting, and modify it to suit your needs.
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 !