Php form emailing but $_POST['email'] is failing - javascript

I have a form on my site that I want to send an email on submit. The email gets sent but none of the content gets sent along with it. It seems that isset($_POST['email']) is failing.
Here is my form:
<form id="sponsorForm" name="sponsor" role="form">
<div class="modal-body">
<div class="form-group col-md-12">
<label for="sponsorname">Name</label>
<input type="text" name="sponsorname" class="form-control">
</div>
<div class="form-group col-md-12">
<label for="sponsoremail">Email</label>
<input type="email" name="sponsoremail" class="form-control">
</div>
<div class="form-group col-md-12">
<label for="sponsormessage">Message</label>
<textarea class="form-control" name="sponsormessage" rows="7" placeholder="Message...">
</textarea>
</div>
</div>
<div class="modal-footer" style="border: none;">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" class="btn btn-success" data-toggle="modal" data-target="#sponsor-thanks" id="sponsor-submit">
</div>
</form>
Here is some javascript to call the php:
$(document).ready(function(){
$("#sponsorForm").submit(function(event){
submitSponsorForm();
return false;
});
});
function submitSponsorForm(){
$.ajax({
type: "POST",
url: "sendSponsor.php",
cache:false,
data: $('form#sponsorForm').serialize(),
success: function(response){
$("#sponsor").html(response)
$("#sponsor-modal").modal('hide');
},
error: function(){
alert("Error");
}
});
}
And here is the php:
<?php
if (isset($_POST['email'])) {
$sponsorname = strip_tags($_POST['sponsorname']);
$sponsoremail = strip_tags($_POST['sponsoremail']);
$sponsormessage = strip_tags($_POST['sponsormessage']);
$message = "Name: ".$sponsorname."\r\nEmail: ".$sponsoremail."\r\nMessage: ".$sponsormessage;
}
mail("xxx#xxx.com", "subject", $message, "from: xxx");
?>

In your form, the name of your email input field is 'sponsoremail'
So you should use the name sponsoremail as the index of $_POST variable as $_POST['sponsoremail'] to check if user fill the email or not but you have used $_POST['email'] which is not found in your form.
Use if (isset($_POST['sponsoremail'])) instead of if (isset($_POST['email'])) and it should work.

Try this
<?php
if (isset($_POST['sponsoremail'])) {
$sponsorname = strip_tags($_POST['sponsorname']);
$sponsoremail = strip_tags($_POST['sponsoremail']);
$sponsormessage = strip_tags($_POST['sponsormessage']);
$message = "Name: ".$sponsorname."\r\nEmail: ".$sponsoremail."\r\nMessage: ".$sponsormessage;
mail("xxx#xxx.com", "subject", $message, "from: xxx");
}
?>

Related

Perform two task with jQuery and php

I have a form which a user fills in, the data is sent to my email, but I also wanted email to be posted to my mail chimp using api but it's not working at the moment.
Here is my form:
<form method="POST" onsubmit="return false;" id="dealerForm ">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input id="subject" name="subject" value="Dealer partner message" type="hidden">
<input class="form-control" placeholder="Your Name *" id="name" name="name" required="" type="text">
</div>
<div class="form-group">
<input class="form-control" placeholder="Your Email *" id="email" name="email" required="" type="email">
</div>
<div class="form-group">
<input class="form-control" placeholder="Your Phone *" id="phone" name="phone" required="" type="tel">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<textarea class="form-control" placeholder="Your Dearlership Info *" id="message" name="message" required=""></textarea>
</div>
</div>
<div class="clearfix"></div>
<div class="col-lg-12 text-right">
<button type="submit" class="btn send_msg">Send Message</button>
</div>
</div>
</form>
Here is my php with mail chimp api and mail send.
<?php
// Email address verification
function isEmail($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL);
}
if($_POST) {
$mailchimp_api_key = 'myapikey'; // enter your MailChimp API Key
// ****
$mailchimp_list_id = 'mylistID'; // enter your MailChimp List ID
// ****
$subscriber_email = addslashes(trim($_POST['email']));
if(!isEmail($subscriber_email)) {
$array = array();
$array['valid'] = 0;
$array['message'] = 'Not a valid email address!';
echo json_encode($array);
}
else {
$array = array();
$merge_vars = array();
require_once 'mailchimp/php/MailChimp.php';
$MailChimp = new \Drewm\MailChimp($mailchimp_api_key);
$result = $MailChimp->call('lists/subscribe', array(
'id' => $mailchimp_list_id,
'email' => array('email' => $subscriber_email),
'merge_vars' => $merge_vars,
'double_optin' => false,
'update_existing' => true,
'replace_interests' => false,
'send_welcome' => true,
));
if($result == false) {
$array['valid'] = 0;
$array['message'] = 'An error occurred! Please try again later.';
}
else {
$array['valid'] = 1;
$array['message'] = 'Success! Please check your mail.';
}
echo json_encode($array);
}
}
if (isset($_POST["email#mail.com"])) {
$to = 'mail#mail.com';
$subject = $_POST['subject'];
$message = 'Name: '.$_POST["name"].'<br>Email: '.$_POST["email"].'<br>Phone: '.$_POST["phone"].'<br>Message: '.$_POST["message"];
$headers = 'From: ' . $_POST["email"] . "\r\n" .
'Reply-To: ' . $_POST["email"] . "\r\n" .
'Content-type: text/html; charset=iso-8859-1;';
if(mail($to, $subject, $message, $headers)){
echo "New record created successfully";
}
}
?>
While my JQuery code:
$("#dealerForm").on("submit", function(){
//debugger;
$.ajax({
type: 'POST',
var url;
url: "contact/dealer.php",
data: $("#dealerForm").serialize()
}).done(function (data) {
//debugger;
console.log(data);
window.location.href = "https://example.com/Thank%20You.html";
});
$("#dealerForm")[0].reset();
return false;
});
Thanks for your comment and your help.
Before mail-chimp fix I think you need to fix followings:
You don't need to use onsubmit="return false;" in form declaration. You already returned false in jQuery onsubmit. And also remove space from form ID name. So, your form declaration can be like <form method="POST" id="dealerForm">
Remove var url; from ajax
Now debug email/mailchimp code in dealer.php.

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');
}
}
}

message alert not working

this my code and the problem is that when i am sending email call form id then email is not sending when i remove form id then email is sending
Htmlcode and after html is js code
this my code and the problem is that when i am sending email call form id then email is not sending when i remove form id then email is sending
<form id="main-contact-form" class="contact-form" name="contact-form" method="post" action="sendemail.php">
<div class="col-sm-5 col-sm-offset-1">
<div class="form-group">
<label>Name *</label>
<input type="text" name="name" class="form-control" required="required">
</div>
<div class="form-group">
<label>Email *</label>
<input type="email" name="email" class="form-control" required="required">
</div>
<div class="form-group">
<label>Phone</label>
<input type="number" class="form-control">
</div>
<div class="form-group">
<label>Company Name</label>
<input type="text" class="form-control">
</div>
</div>
<div class="col-sm-5">
<div class="form-group">
<label>Subject *</label>
<input type="text" name="subject" class="form-control" required="required">
</div>
<div class="form-group">
<label>Message *</label>
<textarea name="message" id="message" required="required" class="form-control" rows="8"></textarea>
</div>
<div class="form-group">
<button type="submit" name="submit" class="btn btn-primary btn-lg" required="required">Submit Message</button>
</div>
</div>
</form>
--
ajax code
var form = $('#main-contact-form');
form.submit(function(event) {
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
$.ajax({
url: $(this).attr('action'),
beforeSend: function() {
form.prepend(form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>').fadeIn());
}
}).done(function(data) {
form_status.html('<p class="text-success">' + data.message + '</p>').delay(3000).fadeOut();
});
});
php code
<?php
header('Content-type: application/json');
$status = array(
'type'=>'success',
'message'=>'Thank you for contact us. As early as possible we will contact you '
);
$name = #trim(stripslashes($_POST['name']));
$email = #trim(stripslashes($_POST['email']));
$subject = #trim(stripslashes($_POST['subject']));
$message = #trim(stripslashes($_POST['message']));
$email_from = $email;
$email_to = 'email#email.com';//replace with your email
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$success = #mail($email_to, $subject, $body, 'From: <'.$email_from.'>');
echo json_encode($status);
die;
This is what your ajax call should look like
$('#main-contact-form').on('submit', function(event) {
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
$.ajax({
url : $(this).attr('action'),
data : $(this).serialize(),
dataType : 'json',
type : 'POST',
beforeSend : function() {
form.prepend(form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>').fadeIn());
}
}).done(function(data) {
form_status.html('<p class="text-success">' + data.message + '</p>').delay(3000).fadeOut();
});
});
make sure your ajax response which is
function(data)
is really an object variable
because if not this code will not execute because of error of data.message
form_status.html('<p class="text-success">' + data.message + '</p>').delay(3000).fadeOut();
also kindly check your network status check the response of that ajax request
using the dev tools F12
UPDATED ANSWER BELOW
so your response is json but still need to be parse in your javascript.
SOLUTION: Parse your ajax response to make it json object
data = JSON.parse(data);
form_status.html('<p class="text-success">' + data.message + '</p>').delay(3000).fadeOut();
The problem is, that you don't send your form data with the ajax-call.
Like adeneo wrote, you only have to add one line to your code.
data : $(this).serialize(),
Setting the data-type is relevant, because the destination needs to know in which format the data is sent.
Try using the Jquery-POST-function. It looks much better in the code.

Php File For HTML Php form

I am studying on a site template for quite long. I have a contact form in my site and my html file (index.html) is linked to a js file (contact-me.js). I'm providing them below :
Contact Form In index.html :
<!-- OPEN - Content -->
<div class="item-title text-center">
<!-- Contact form -->
<form id="contact-form" name="contact-form" method="POST" data-name="Contact Form">
<div class="row">
<!-- Full name -->
<div class="col-xs-12 col-sm-6 col-lg-6">
<div class="form-group">
<input type="text" id="name" class="form form-control" placeholder="Write your name" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Write your name'" name="name" data-name="Name" required>
</div>
</div>
<!-- E-mail -->
<div class="col-xs-12 col-sm-6 col-lg-6">
<div class="form-group">
<input type="email" id="email" class="form form-control" placeholder="Write your email address" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Write your email address'" name="email-address" data-name="Email Address" required>
</div>
</div>
<!-- Subject -->
<div class="col-xs-12 col-sm-12 col-lg-12">
<div class="form-group">
<input type="text" id="subject" class="form form-control" placeholder="Write the subject" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Write the subject'" name="subject" data-name="Subject">
</div>
</div>
<!-- Message -->
<div class="col-xs-12 col-sm-12 col-lg-12 no-padding">
<div class="form-group">
<textarea id="text-area" class="form textarea form-control" placeholder="Your message here... 20 characters Min." onfocus="this.placeholder = ''" onblur="this.placeholder = 'Your message here... 20 characters Min.'" name="message" data-name="Text Area" required></textarea>
</div>
</div>
</div>
<!-- Button submit -->
<button type="submit" id="valid-form" class="btn btn-color">Send my Message</button>
</form>
<!-- /. Contact form -->
<div id="block-answer">
<div id="answer"></div>
</div>
</div> <!-- CLOSE - Content -->
and my contact-me.js is :
$(document).ready(function() {
$("#contact-form [type='submit']").click(function(e) {
e.preventDefault();
// Get input field values of the contact form
var user_name = $('input[name=name]').val();
var user_email = $('input[name=email-address]').val();
var user_subject = $('input[name=subject]').val();
var user_message = $('textarea[name=message]').val();
// Datadata to be sent to server
post_data = {'userName':user_name, 'userEmail':user_email, 'userSubject':user_subject, 'userMessage':user_message};
// Ajax post data to server
$.post('php/contact-me.php', post_data, function(response){
// Load json data from server and output message
if(response.type == 'error') {
output = '<div class="error-message"><p>'+response.text+'</p></div>';
} else {
output = '<div class="success-message"><p>'+response.text+'</p></div>';
// After, all the fields are reseted
$('#contact-form input').val('');
$('#contact-form textarea').val('');
}
$("#answer").hide().html(output).fadeIn();
}, 'json');
});
// Reset and hide all messages on .keyup()
$("#contact-form input, #contact-form textarea").keyup(function() {
$("#answer").fadeOut();
});
});
Can You Please Help Me With The php file. I am completely new to php. Please help me with the php file that I should use for this form.
Here is a sample code.
You need a basic understanding of POST and GET method and read the PHP manual on how to use 'mail()'
<?php
$to = "mail#yourdomain.com";
$from = $_POST['user_email'];
$name = $_POST['user_name'];
$headers = "From: $from";
$subject = $_POST['user_subject'];
$body = $_POST['user_message'];
$send = mail($to, $subject, $body, $headers);
?>
I assumed that you need a php script to send you the data on your mail that user enters
I seriously have no idea why you are using Javascript(you are not verifying data,so use post action method of php. just add action="somename.php" in form tag,somewat like this
<form id="contact-form" name="contact-form" method="POST" action="somename.php">
and in somename.php keep the following content
<?php
$name = $_POST['name'];
$usermail = $_POST['email-address'];
$message = $_POST['message'];
$to = "yourmail#example.com";
$subject = $_POST['subject'];
$text = "Name-" . $name ."\nEmail-" . $usermail ."\nMessage-" . $message;
$headers = "From: webmaster#yourdomain.com" . "\r\n" .
"CC: somebodyelse#example.com";
mail($to,$subject,$text,$headers);
?>
You may continue using javascript(if so dont add action to form tag).

How can i submit hidden values to php using AJAX

i am trying to send some values from html form to php page.
here in the form i have some values which are hidden.and one text field which its value has to be passed to php page.
index.php:
<?php
if ($login->isUserLoggedIn() == true){
?>
<div class="panel panel-default">
<div class="panel-heading"><h4>Invite friend</h4></div>
<div class="panel-body">
<form action="friend-invite.php" method="get">
<div class="col-md-4 col-lg-4">
<label class="control-label" for="friend">Enter email address</label>
<input type="email" class="form-control" name="friendemail" id="friendemail" placeholder="sam#uncle.com" required><br>
<?php
echo '<input type="hidden" name="invitename" value="'.$_SESSION["user_name"].'">' ;
echo '<input type="hidden" name="invite-url" value="'.$_SERVER['REQUEST_URI'].'">';
echo '<input type="hidden" class="invite-product" name="invite-product-name">';
?>
<input type="submit" name="submit" value="Invite" class="btn btn-primary">
</div>
</form>
<div class="mail-message"></div>
</div>
</div>
<?php
}else{
}?>
friend-invite.php:
<?php
include('_header.php');
$user_email = $_GET['friendemail'];
$invited_by = $_GET['invitename'];
$invite_link = $_GET['invite-url'];
$product_name = $_GET['invite-product-name'];
if (isset($user_email, $invited_by, $invite_link, $product_name)){
sendInvitation($user_email,$invited_by,$invite_link,$product_name);
} else {
echo "Are you trying to do something nasty??";
}
function sendInvitation($user_email,$invited_by,$invite_link,$product_name)
{
$mail = new PHPMailer;
if (EMAIL_USE_SMTP) {
$mail->IsSMTP();
$mail->SMTPAuth = EMAIL_SMTP_AUTH;
if (defined(EMAIL_SMTP_ENCRYPTION)) {
$mail->SMTPSecure = EMAIL_SMTP_ENCRYPTION;
}
$mail->Host = EMAIL_SMTP_HOST;
$mail->Username = EMAIL_SMTP_USERNAME;
$mail->Password = EMAIL_SMTP_PASSWORD;
$mail->Port = EMAIL_SMTP_PORT;
$mail->IsHTML(true);
} else {
$mail->IsMail();
}
$mail->From = EMAIL_VERIFICATION_FROM;
$mail->FromName = $invited_by;
$mail->AddAddress($user_email);
$mail->Subject = SHOP_INVITE;
$link = $invite_link;
$mail->Body = $invited_by." ".FRIEND_INVITE_PRODUCT."<a href='".$link."'>".$product_name."</a>";
if(!$mail->Send()) {
$this->errors[] = MESSAGE_VERIFICATION_MAIL_NOT_SENT . $mail->ErrorInfo;
return false;
} else {
return true;
}
}
?>
AJAX function:
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'get',
url: 'invite-friend.php',
data: $('form').serialize(),
success: function () {
$(".mail-message").html('<div class="alert alert-success"><strong>Success!</strong> Indicates a successful or positive action.</div>');
}
});
});
});
the friend-invite.php page is getting the values that has been passed to it and check if the values has been set, if it has been set then it will call the php function sendInvitation() with the parameters. now all these things are happening pretty good.but i want to do it through AJAX. how can i do that.
You forgot to give your hidden fields an id:
echo '<input type="hidden" name="invitename" id="invitename" value="'.$_SESSION["user_name"].'">' ;
...
Change your index.php as:
<?php
if ($login->isUserLoggedIn() == true){
?>
<div class="panel panel-default">
<div class="panel-heading"><h4>Invite friend</h4></div>
<div class="panel-body">
<form action="">
<div class="col-md-4 col-lg-4">
<label class="control-label" for="friend">Enter email address</label>
<input type="email" class="form-control" name="friendemail" id="friendemail" placeholder="sam#uncle.com" required><br>
<?php
echo '<input type="hidden" name="invitename" value="'.$_SESSION["user_name"].'">' ;
echo '<input type="hidden" name="invite-url" value="'.$_SERVER['REQUEST_URI'].'">';
echo '<input type="hidden" class="invite-product" name="invite-product-name">';
?>
<input type="button" id="btn-submit" name="submit" value="Invite" class="btn btn-primary" />
</div>
</form>
<div class="mail-message"></div>
</div>
</div>
<?php
}else{
}?>
And change AJAX function as:
$(function () {
$('#btn-submit').on('click', function (e) {
e.preventDefault();
$.ajax({
type: 'get',
url: 'invite-friend.php',
data: $('form').serialize(),
success: function () {
$(".mail-message").html('<div class="alert alert-success"><strong>Success!</strong> Indicates a successful or positive action.</div>');
}
});
});
});
We do not need a submit button in form if we using AJAX.
Dude you are simply making your code complex ... you are doing form submit + ajax submit .I think there you are going wrong.
Just try these:
Remove action="friend-invite.php" from your form tag and try . if this does not help than make your button input type button or use button tag. just try all these it should work.
If all this does not work than give id and name to your form ,,and use to submit as:
$(function() {
$("#form_id").on("submit", function(event) {
Try all these

Categories

Resources