php ajax one page contact form - javascript

i am working on one page ajax contactform . I want to send an email with PHP without leaving my page and now i'm completely lost. I have no idea why its not working
i'll show you my contact form. thank you for help in advance. Here is the form ..
html code
<article class="panel" style="background:url(img/cover/bg_panel_3.jpg); background-size:cover;" full-screen>
<div style="padding-top:80px;">
<div class="row text-center centered">
<div id="contact-form">
<form id="contact-us" action="contact.php" method="post">
<ul>
<li class="field" id="check-1">
<input class="input txt requiredField wide alpha-only" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" placeholder="Name" onBlur="check(this.value)" />
</li>
<li class="field" id="check-2">
<input class="input wide mail-only txt requiredField email" name="email" id="email" value="<?php if(isset($_POST['email'])) echo $_POST['email'];?>" placeholder="Email" />
</li>
<li class="field" id="check-3">
<input class="input wide hack-check sub-check requiredField" name="subj" type="text" placeholder="Subject" value="<?php if(isset($_POST['subj'])) echo $_POST['subj'];?>" />
</li>
<li class="field" id="check-4">
<input class="input wide num-only requiredField" name="num" type="text" placeholder="Number" value="<?php if(isset($_POST['num'])) echo $_POST['num'];?>" />
</li>
<li class="field" id="check-5">
<textarea class="input textarea wide hack-check msg-check txtarea requiredField" name="comments" id="commentsText" class="txtarea requiredField" placeholder="Message:">
<?php if(isset($_POST['comments'])) { if(function_exists('stripslashes')) { echo stripslashes($_POST['comments']); } else { echo $_POST['comments']; } } ?>
</textarea>
</li>
</ul>
<div class="medium primary btn pretty-btn">
<input name="submit" class="subbutton" type="submit" value="Send" />
</div>
<input type="hidden" name="submitted" id="submitted" value="true" />
</form>
<?php } ?>
<!-- End #contact -->
</div>
</div>
</div>
</article>
**js code **
$(document).ready(function() {
$('form#contact-us').submit(function() {
$('form#contact-us .error').remove();
var hasError = false;
});
if(!hasError) {
var formInput = $(this).serialize();
alert(formInput);
$.post("contact-us.php",formInput, function(data){
$('form#contact-us').slideUp("fast", function() {
$(this).before('<p class="tick fg-white sans"><strong>Thanks!</strong> Your email has been delivered. !</p>' );
});
});
}
return false;
});
});
PHP Code
//If the form is submitted
if(isset($_POST['submitted'])) {
$name = trim($_POST['contactName']);
$email = trim($_POST['email']);
$num = trim($_POST['num']);
$subject = trim($_POST['subj']);
$comments = trim($_POST['comments']);
$formcontent=" From : $name \n Email : $email \n Subject : $subj \n Phone number : $number \n \n Message : $message";
$recipient = "example#mail.com";
$subject = "Contact Form Query Received";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error encountered! Please try again or write directly to the mentioned email address.");
// set our boolean completion value to TRUE
$emailSent = true;
}

I suspect your problem is this extra }); in your code which is stopping the $.post(...) call from even being called. A quick lint of your JS shows this up, as does careful reading.
var hasError = false;
======> }); <====== remove this extra stuff.
if(!hasError) {

Related

Custom Form in WordPress Page Won't Submit/Refresh

I had a normal site that I built with custom HTML/CSS/JS. I changed the site to become a WordPress site (and made my custom html/css/js into a custom WordPress theme). I had a contact form on the homepage of the site, which broke when I made the change to WordPress.
When the form was functioning, it would refresh the page and bring the user back down to the form (using the anchor id=contactphilly) and then the user would see a message confirming their email was sent.
I did a LOT of Googling and I think it has something to do with the "action" option in the form, but no matter what I try changing it to, it doesn't work. I tried the following for the action value:
<?php the_permalink(); ?>/#contactphilly
#contactphilly
<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>
$_SERVER['REQUEST_URI']
None of them worked.
Here is the code for the form:
<?php
if (isset($_POST["submit"])) {
$name = $_POST['name'];
$subject = $_POST['subject'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'WebKeep.com';
$to = 'info#webkeepteam.com';
$subjectemail = 'Message from WebKeepTeam.com Contact Form ';
$body = "From: $name\n E-Mail: $email\n Subject: $subject\n Message:\n $message";
// Check if name has been entered
if (!$_POST['name']) {
$errName = 'Please enter your name';
}
// Check if email has been entered and is valid
if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errEmail = 'Please enter a valid email address';
}
//Check if message has been entered
if (!$_POST['message']) {
$errMessage = 'Please enter your message';
}
// If there are no errors, send the email
if (!$errName && !$errEmail && !$errMessage) {
if (mail ($to, $subjectemail, $body, $from)) {
$result='<div>Thank You! We will respond shortly.</div>';
} else {
$result='<div>Sorry there was an error sending your message. Please try again later</div>';
}
}
}
?>
and
<form name="contactform" method="post" action="#contactphilly">
<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
<fieldset class="form-group">
<input type="text" value="<?php echo $name;?>" class="form-control transparent-input" id="name" name="name" placeholder="Name">
</fieldset>
<?php echo "<p class='text-danger'>$errName</p>";?>
<fieldset class="form-group">
<input type="email" value="<?php echo $email;?>" class="form-control transparent-input" id="email" name="email" placeholder="Email">
</fieldset>
<?php echo "<p class='text-danger'>$errEmail</p>";?>
<fieldset class="form-group">
<input type="text" class="form-control transparent-input" value="<?php echo $subject;?>" id="subject" name="subject" placeholder="Subject">
</fieldset>
</div>
<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
<fieldset class="form-group">
<textarea class="form-control transparent-input" id="message" value="<?php echo $message;?>" name="message" rows="6" placeholder="Message"><?php echo htmlspecialchars($_POST['message']);?></textarea>
</fieldset>
<?php echo "<p class='text-danger'>$errMessage</p>";?>
<input id="submit" name="submit" type="submit" value="Send" class="btn btn-index pull-right">
</div>
<?php echo $result; ?>
</form>
I found an answer to my own question! I completely forgot about this bit of code on GitHub: https://github.com/dwyl/html-form-send-email-via-google-script-without-server I used it elsewhere on the site and it worked, and it also works beautifully for forms within pages too!

How to display success popup message after clicking on submit button in codeigniter php

Displaying a custom popup message as thank you after clicking on submit button.I have used codeigniter framework.I have a section as request form once the user filled the data and clicked on submit button a pop up message should be displayed on that section as thank you message.Here is my code.
<div class="col-md-3 requestfree">
<img src="<?= base_url(); ?>theme/images/icon1.png" class="requesting">
<h3 class="request">REQUEST</h3>
<h5 class="free"> FREE QUOTE</h5>
<h5 class="receive">You will receive quote within 24 hours</h5>
<form name="contact" id="contactform" enctype="multipart/form-data" method="post" action="<?php echo base_url();?>welcome/request">
<?php if (isset($msg)): ?>
<?= $msg; ?>
<?php endif; ?>
<div class="name"><span class="mandatory"></span>
<input type="text" class="form-control" name="name" placeholder="Name" required>
<?= form_error('name', '<div class="error">', '</div>'); ?>
</div>
<div class="name">
<input type="text" class="form-control" name="phone" placeholder="Phone" required>
<?= form_error('phone', '<div class="error">', '</div>'); ?>
</div>
<div class="email">
<input type="email" class="form-control" name="email" placeholder="Email" required>
<?= form_error('email', '<div class="error">', '</div>'); ?>
</div>
<div class="description">
<textarea name="description" style="width:100%;overflow:auto;" placeholder="Description" required></textarea>
</div>
<div class="">
<div class="captchas">
<img src="captcha.php?rand=<?= rand(); ?>" class="captchass" id='captchaimg'/>
<p class="change">click to change</p>
</div>
<div class="captcha">
<input type="text" class="form-control"id="captcha_code" name="captcha_code" style="background-color: #EAD5D2;border: none;">
</div>
</div>
<button type="submit" class="btn btn-success" onclick="return validate();">Submit</button>
<p class="privacy">We respect your privacy</p>
</form>
</div>
Controller:
function request()
{
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<br /><span class="error"> ','</span>');
$this->form_validation->set_rules('name','First Name' , 'required');
$this->form_validation->set_rules('email','Email','required|valid_email');
$this->form_validation->set_rules('phone','Mobile Number','required|numeric');
$this->form_validation->set_rules('description','Description','required');
if($this->form_validation->run()== FALSE)
{
$data['mainpage']='index';
$this->load->view('templates/template',$data);
}
else
{
echo "hi";
//get the form data
$name = $this->input->post('name');
$from_email = $this->input->post('email');
$phone = $this->input->post('phone');
$description = $this->input->post('description');
//set to_email id to which you want to receive mails
$to_email = 'gmail#gmail.com';
$config=Array(
'protocol'=> 'smtp',
'smtp_host' => 'ssl://smtp.gmail.com', //smtp host name
'smtp_port' => '465', //smtp port number
'smtp_user' => 'mail#gmail.com',
'smtp_pass' => '*******', //$from_email password
'mailtype' =>'html',
'newline' =>"\r\n",
'crlf' =>"\r\n",
'charset' => 'iso-8859-1',
'wordwrap' => TRUE
);
$message = array();
$message[] = 'Username : '.trim($name).' ';
$message[] = 'Phone Number : '.trim($phone).' ';
$message[] = 'Description : '.trim($description).' ';
$message = implode(PHP_EOL, $message);
//send mail
$this->load->library('email',$config);
$this->email->from($from_email);
$this->email->to($to_email);
$this->email->subject('Request Free Quote');
$this->email->message($message);
$this->email->set_newline("\r\n");
if ($this->email->send())
{
// mail sent
$this->session->set_flashdata('msg','<div class="alert alert-success text-center">Your mail has been sent successfully!</div>');
redirect('welcome');
}
else
{
//error
$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">There is error in sending mail! Please try again later</div>');
redirect('welcome');
}
}
}

Need to process a contact form

I purchased a theme, and I need to make a processing.php for my contact form. The form that sends the data to the server for processing.
This is the form code:
<div class="form_error text-center">
<div class="name_error hide error">Please Enter your name</div>
<div class="email_error hide error">Please Enter your Email</div>
<div class="email_val_error hide error">Please Enter a Valid Email Address</div>
<div class="message_error hide error">Please Enter Your Message</div>
</div>
<div class="Sucess"></div>
<form role="form">
<div class="row">
<div class="col-md-4">
<input type="text" class="form-control" id="name" placeholder="Name">
<input type="email" class="form-control" id="email" placeholder="Email">
<input type="text" class="form-control" id="subject" placeholder="Subject">
</div>
<div class="col-md-8">
<textarea class="form-control" id="message" rows="25" cols="10" placeholder=" Message Texts..."></textarea>
<button type="button" class="btn btn-default submit-btn form_submit">SEND MESSAGE</button>
</div>
</div>
</form>
Both shubham and adi's answers are vulnerable to SMTP header injections, allowing your contact form to be used to send spam. It will happen.
Any POST or GET data passed to the additional_headers parameter needs to be sanitised to prevent abuse.
See the following:
http://php.net/manual/en/function.mail.php
https://www.phpsecure.info/v2/article/MailHeadersInject.en.php
see this example
<?php
if(isset($_POST['submit'])){
$to = "email#example.com"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$subject = "Form submission";
$subject2 = "Copy of your form submission";
$message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['message'];
$message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
// You can also use header('Location: thank_you.php'); to redirect to another page.
}
?>
<!DOCTYPE html>
<head>
<title>Form submission</title>
</head>
<body>
<form action="" method="post">
First Name: <input type="text" name="first_name"><br>
Last Name: <input type="text" name="last_name"><br>
Email: <input type="text" name="email"><br>
Message:<br><textarea rows="5" name="message" cols="30"></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
<?php
if (isset($_POST['contact_name'])&&isset($_POST['contact_mail'])&&isset($_POST['message'])) {
$contact_name = $_POST['contact_name'];
$contact_mail = $_POST['contact_mail'];
$message = $_POST['message'];
if (!empty($contact_name) && !empty($contact_mail) && !empty($message)) {
$to = 'your email#gmail.com'; // this is where you want to send the email
$subject = 'Contact form Submitted';
$body = $contact_name."\n".$message;
$headers = 'From:'.$contact_mail; // email of the sender
if (#mail($to, $subject, $body, $headers)) {
echo 'Thanks for contacting us';
}
else {
echo 'Sorry, an error has been occurred';
}
}
else {
echo 'All fields are required';
}
}
?>
<form action="index.php" method="POST">
Name:<br>
<input type="text" name="contact_name"></input><br><br>
Email Address:<br>
<input type="text" name="contact_mail"></input><br><br>
Message:<br>
<textarea name="message" cols="30" rows="6"></textarea><br><br>
<input type="submit" value="Send"></input>
</form>
maybe this codes can help you

How to Save the optins in a text file without disturbing the email notif

I am using a custom optin page with a form , I want to tweak it a little bit,
I want to save all the optins on a txt file on the server without
disturbing the other functions of the form.
2nd thing I want is to show a custom Page after the optin form is
submitted.
Currently the form works like this
USER SUBMITS > PAGE REFRESHES FOR HIM > I GET AN EMAIL WITH THE SUBMITTED DATA.
Here is the form code
<div class="form fix ">
<p class="form-text">Fill This Out and See Your <br>Timeshare Report</p>
<form name="contactform" action="mail-script.php" method="POST">
<label for="fname">First Name:
<input type="text" name="fname" id="fname" />
</label><br>
<label for="lname">Last Name:
<input type="text" name="lname" id="lname" />
</label><br>
<label for="email">Email Address:
<input type="text" name="email" id="email" />
</label><br>
<label for="phone">Phone Number:
<input type="text" name="phone" id="phone" />
</label><br>
<label for="phone">Alternate Phone:
<input type="text" name="phone" id="aphone" />
</label><br>
<label for="resort">Resort Name:
<input type="text" name="resort" id="resort" />
</label><br>
<label for="amount">Amount Owed? $:
<input type="number" name="amount" id="amount" />
<p style="font-size: 12px !important;margin-top: -14px;padding-right: 30px;text-align:right;">
If Paid Off Leave Zero, Else Put Amount</p>
</label><br>
<div class="checkbox">
<div class="check-text fix">
<p>I'm Considering To</p>
</div>
<div class="check-one fix">
<input type="checkbox" name="call" id="" value="sell"/> Sell It <br>
<input type="checkbox" name="call" id="" value="buy"/> Buy It <br>
<input type="checkbox" name="call" id="" value="rent "/> Rent It
</div>
<div class="check-two fix">
<input type="checkbox" name="call" id="" value="cancel"/> Cancel Mortgage <br>
<input type="checkbox" name="call" id="" value="ownership"/> End Ownership <br>
<input type="checkbox" name="call" id="" value="give"/> Give It Back
</div>
</div>
<p class="captcha">
<img src="captcha_code_file.php?rand=<?php echo rand(); ?>" id='captchaimg' ><br>
<label for='message'>Enter the code above here :</label><br>
<input id="6_letters_code" name="6_letters_code" type="text"><br>
<small>Can't read the image? click <a href='javascript: refreshCaptcha();'>here</a> to refresh</small>
</p>
<input id="submit" type="submit" value="" />
<p class="submit-text">Ensure all fields are completed and correct, allowing you more benefits, while preventing abuse of our data.</p>
</form>
</div>
</div>
This is the mail script which sends me the email
<?php
/* Set e-mail recipient */
$myemail = "**MYEMAIL**";
/* Check all form inputs using check_input function */
$fname = check_input($_POST['fname'], "Enter your first name");
$lname = check_input($_POST['lname'], "Enter your last name");
$email = check_input($_POST['email']);
$phone = check_input($_POST['phone']);
$resort = check_input($_POST['resort']);
$amount = check_input($_POST['amount']);
$call = check_input($_POST['call']);
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
show_error("E-mail address not valid");
}
/* If URL is not valid set $website to empty */
if (!preg_match("/^(https?:\/\/+[\w\-]+\.[\w\-]+)/i", $website))
{
$website = '';
}
/* Let's prepare the message for the e-mail */
$message = "Hello!
Your contact form has been submitted by:
First Name : $fname
Last Name : $lname
E-mail: $email
Phone : $phone
Resort: $resort
Amount: $amount
Call : $call
End of message
";
/* Send the message using mail() function */
mail($myemail, $subject, $message);
/* Redirect visitor to the thank you page */
header('Location: index.html');
exit();
/* Functions we used */
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}
function show_error($myError)
{
?>
if (strtolower($_POST['code']) != 'mycode') {die('Wrong access code');}
<html>
<body>
<b>Please correct the following error:</b><br />
<?php echo $myError; ?>
</body>
</html>
<?php
exit();
}
?>
Here is the online url of the page http://timesharesgroup.com/sell/index.html
you can add this code to your script after all the validation is done:
$text = "$fname\n$lname\n$email\n$phone\n$resort\n$amount\n$call\n\n";
file_put_contents('file.txt', $text, FILE_APPEND);
OR even better csv file:
$fields = array($fname,$lname,$email,$phone,$resort,$amount,$call);
$fp = fopen('file.csv', 'a');
fputcsv($fp, $fields);
fclose($fp);

How to get a msgbox?

I am creating a simple enquiry form with upload option.
If I click submit button it goes to another page and displays success message but it should come in the same page as a message box. What should I do?
Here is my Html code:
<ul>
<li><span>Name</span>
<input name="name" type="text" size="25" class="text1" />
</li>
<li><span>Contact</span>
<input name="contact" type="text" size="25" class="text2" />
</li>
<li><span>E-mail</span>
<input name="email" type="text" size="25" class="text3" />
</li>
<li><span>Subject</span>
<input name="subject" type="text" size="25" class="text4" />
</li>
<li><span>Message</span>
<textarea name="message" size="250" class="text5"></textarea>
</li>
</ul>
<label for="upload"></label>
<div class="x">
<input type="file" name="upload" id="file" class="button">
</div>
<div class="x1">
<input type="submit" name="submit" value="Submit" class="button" />
</div>
And this is my PHP code for uploading and inserting:
<?php
$target = "upload/";
$target = $target . basename($_FILES['upload']['name']);
$ok = 1;
if (move_uploaded_file($_FILES['upload']['tmp_name'], $target))
{
echo "The file " . basename($_FILES['upload']['name']) . " has been uploaded";
}
else
{
echo "Sorry, there was a problem uploading your file.";
}
?>
<?php
include ("conn.php");
if (isset($_POST['submit']))
{
$sql="insert into cform (name,contact,email,subject,message,upload)values('".$_POST['name']."','".$_POST['contact']."','".$_ POST['email']."','".$_POST['subject']."','".$_POST['message']."','$target')";
$result=mysql_query($sql);
if (!$result)
{
echo "could not enter data";
}
else
{
echo "successfuly entered";
}
}
?>
This PHP page has to run in background and when I click the submit button a message box should display success.
Edit the echo portion of the page as
second page
$rspnse = "";
if(!$result){
$rspnse = "Error";
}
else{
$rspnse = "Success";
}
header('Location: previous_page.php?response='.$rspnse);
Replace the previous_page.php with your original url of the first page
first page
<?php
if(isset($_GET['response'])){
?>
<script>
alert('<?php echo $_GET['response'] ?>');
</script>
<?php
}
?>
Hope this helps...
if(! $result) {
$msg = "could not enter data";
}else{
$msg = "successfuly entered";
}
header('Location: http://www.example.com/form.php?message=$msg');
//Redirect to form page with set message.
add script in form page to display message
if(isset($_GET['message'])){
print $_GET['message'];
}
This solution for as per your code
And another option is using ajax.

Categories

Resources