So I am currently utilizing a HTML form to obtain information from customers (in a landing page context) that sends via email all the information that the user submitted, and it's working fine so far.
However, I've added a file upload field to the HTML form ($userfile) but I wasn't able to handle the file upload and attachment properly. I've been testing and tweaking around a lot, but I can never seem to get it working.
This is the PHP file that I'm currently utilizing, based on a pre-existing template.
$to = "email#email.com";
$nome = $_POST["nome"];
$email = $_POST["email"];
$website = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
if (isset($email) && isset($nome)) {
$subject = "Lead: $nome";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= "From: ".$nome." <".$email.">\r\n"."Reply-To: ".$email."\r\n" ;
$msg = 'Hey Admin, <br/> <br/> Here are the details:';
$msg .= ' <br/> <br/> <table border="1" cellpadding="6" cellspacing="0" style="border: 1px solid #eeeeee;">';
foreach ($_POST as $label => $value) {
$msg .= "<tr><td width='100'>". ucfirst($label) . "</td><td width='300'>" . $value . " </tr>";
}
$msg .= " </table> <br> --- <br>Sent by $website";
$mail = mail($to, $subject, $msg, $headers);
if($mail) {
echo 'success';
} else {
echo 'failed';
}
} // END isset
?>
And also the AJAX POST
var dataString = $(form).serialize();
/*
AJAX POST
--------- */
$.ajax({
type: "POST",
data: dataString,
url: "php/contact.php",
cache: false,
success: function(d) {
$(".form-group").removeClass("has-success");
if (d == 'success') {
if (noredirect) {
$('#js-contact-result').fadeIn('slow').html('<div class="alert alert-success top-space">' + success_msg + '</div>').delay(3000).fadeOut('slow');
} else {
window.location.href = redirect;
}
} else {
$('#js-contact-result').fadeIn('slow').html('<div class="alert alert-danger top-space">' + error_msg + '</div>').delay(3000).fadeOut('slow');
}
$("#js-contact-btn").attr("disabled", false);
}
});
If anyone could point me to some resources where I can learn more or actually help me solve it, I would really appreciate it. Thank you!
var dataString = $(form).serialize();
does not allow for uploading files
instead use a formdata javascript object
var dataString = new FormData(form);
You cannot use form.serialize() for file input.
Check here: jQuery Ajax File Upload
Related
I have a simple POST script for PHP which sends an email, but when I click the submit button it executes and then goes to the script directory (ex: localhost/sendMail/test.php). Is it possible to post an alert box, and then stay on the page instead of going to the script and then redirecting back onto the submit page?
This is my script.
<?php
$subject = 'Your website: Contact'; // Subject of your email
$to = 'myemail'; // Enter recipient's E-mail address
$emailTo = $_REQUEST['email'];
$headers = "MIME-Version: 1.1";
$headers .= "Content-type: text/html; charset=iso-8859-1";
$headers .= "From: " . $emailTo . "\r\n"; // Sender's E-mail
$headers .= "Return-Path:". $emailTo;
$body = 'You have received a new inquiry!' . "\n\n";
$body .= 'Name: ' . $_REQUEST['name'] . "\n";
$body .= 'Email: ' . $_REQUEST['email'] . "\n";
$body .= 'Phone: ' . $_REQUEST['phone'] . "\n\n";
$body .= 'Message: ' . $_REQUEST['message'];
if($_REQUEST['name'] != "" && $_REQUEST['email'] != "" && $_REQUEST['phone'] != "" && $_REQUEST['message'] != "")
{
if (#mail($to, $subject, $body, $headers))
{
// Transfer the value 'sent' to ajax function for showing success message.
echo 'sents';
}
else
{
// Transfer the value 'failed' to ajax function for showing error message.
echo 'failed';
}
}
else
{
$message = "Invalid fields!";
echo "<script type='text/javascript'>alert('$message');</script>";
//header("Location: http://localhost/abtek/contact.html");
exit;
}
?>
So when the alert is executed, is it possible to stop it from going to the script, and instead staying on the page until the fields are all valid to submit? As well as when they are submitted to display an alert again and stay on the page instead of doing a bunch of redirects.
Any help would be greatly appreciated.
You can submit the form with ajax/jquery and stop the redirect. See here: Stackoverflow
You can use jQuery, like this:
$('#my-submit').on('click', function(e){
e.preventDefault(); // prevents regular form submission
$.ajax({
url: 'localhost/sendMail/test.php',
data: $('form').serialize(),
success: function(result){
alert('Message: ' + result );
},
error: function(err){
alert(err)
}
})
});
In your PHP you should just do echo $message; to handle error better.
Read all you can about jQuery/AJAX, as there are important options you can explode, like using JSON.
My contact form is not including message and other informations in emails.
There is 'Unknown sender' and 'No subject'. Email contains my tags (from:, subject:, message:) but no content is written after them.
I have tried a few other scripts, but they gave the same result.
My JS code
(function($){
$(document).ready(function() {
$('#submit-form').click(function(e){
e.preventDefault();
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var name = $('#rp_name').val(),
email = $('#rp_email').val(),
subject = $('#rp_subject').val(),
message = $('#rp_message').val(),
data_html,
success = $('#success');
if(name === ""){
$('#rp_name').val('Please enter your name.');
}
if(subject === ""){
$('#rp_subject').val('Please enter your name.');
}
if(email === ""){
$('#rp_email').val('Your email is required.');
}else if(reg.test(email) === false){
$('#rp_email').val('Invalid Email Address.');
}
if(message === ""){
$('#rp_message').val('Message is required.');
}
if(message !== "" && name !== "" && reg.test(email) !== false) {
data_html = "name=" + name + "&email="+ email + "&message=" + message + "&subject="+ subject;
alert(data_html);
$.ajax({
type: 'POST',
url: 'php_helpers/contact_form.php',
data: data_html,
success: function(msg){
if (msg == 'sent'){
success.html('<div class="alert alert-success">Message <strong>successfully</strong> sent!</div>') ;
$('#rp_name').val('');
$('#rp_email').val('');
$('#rp_message').val('');
}else{
success.html('<div class="alert alert-error">Message <strong>not</strong> sent! Please Try Again!</div>') ;
}
}
});
}
return false;
});
});
})(jQuery);
My PHP code
<?php
$to = 'email'; // I changed it
$subject = $_POST['subject'];
if($to) {
$name = $_POST['name'];
$email = $_POST['email'];
$fields = array(
0 => array(
'text' => 'Imie',
'val' => $_POST['name']
),
1 => array(
'text' => 'Email',
'val' => $_POST['email']
),
2 => array(
'text' => 'WIADOMOSC',
'val' => $_POST['message']
)
);
$message = "";
foreach($fields as $field) {
$message .= $field['text'].": " . htmlspecialchars($field['val'], ENT_QUOTES) . "<br>\n";
}
$$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$headers .= 'From: '. $email . "\r\n" . 'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
if ($message){
echo 'sent';
}else{
echo 'failed';
}
} else {
echo "Don't access this file directly";
}
?>
I'll be glad for any hints.
There as i check your contact.php file code is ok. But you need one thing if use firefox. please console your code.I mean when you open firebug there will be one option console. with help you can check is your value along with variable is going or they empty.
I think your value is not going to PHP file. use console and you can easily bug your value.
I hope this make sense for you.
Check if your php script receives name, email and message. You can check it using
var_dump($_POST);
If server doesn't receive these variables, try to send data_html as an object:
change
data: data_html,
to
data: {name: name, email: email, message: message}
I didn't test it, but I always use this way of sending data from js to server.
You are using two dollar symbols in the line: $$headers = 'MIME-Version: 1.0' . "\r\n"; Please remove "$" and try again.
Thanks for all your responses. I finally manage to find a solution. I haven't used firebug before, but thanks to it I could find the error message. Now the script is working fine.
It wasn't in code, but in .htaccess rewrite rule for .php files which was couseing 301 error for ajax request (../contact instead of ../contact.php).
I have one .php page (file uploader) and I thought that adding another seo-friendly link rule for it would be a good idea.
I got the messege to apear in the DIV tag but not sure how to send the email address onto the external email database //myguestlist.com/mgl/formreceiver.php.
here is the HTML
Be the first to know about the Channel Seven Brisbane Racing
Carnival:
method="post" id="mf528c0a39d76be"> <input class="mailchimp-input"
input="" name="PatronEmail" id="mf528c0a39d76be_PatronEmail"
placeholder="Enter your email..." type="text"> <button type="submit"
class="btn"><span class="singup-image"><img src="img/send.png"
alt="send email"></span><span class="singup-text">Send</span></button>
</form>
<div class="success-message"></div>
<div class="error-message"></div>
</div>
Here is the PHP:
<?php
// Email address verification
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]]).)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]).){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i", $email));
}
if($_POST) {
// Enter the email where you want to receive the notification when someone subscribes
$emailTo = 'wbriton#brc.com.au';
$subscriber_email = ($_POST['PatronEmail']);
if(!isEmail($subscriber_Email)) {
$array = array();
$array['valid'] = 0;
$array['message'] = 'Insert a valid email address!';
echo json_encode($array);
}
else {
$array = array();
$array['valid'] = 1;
$array['message'] = 'Thanks for your subscription!';
echo json_encode($array);
// Send email
$subject = 'New Subscriber!';
$body = "You have a new subscriber!\n\nEmail: " . $subscriber_email;
// uncomment this to set the From and Reply-To emails, then pass the $headers variable to the "mail" function below
//$headers = "From: ".$subscriber_email." <" . $subscriber_email . ">" . "\r\n" . "Reply-To: " . $subscriber_email;
mail($emailTo, $subject, $body);
}
}
?>
And here is the Java Script
$('.success-message').hide();
$('.error-message').hide();
$('.subscribe form').submit(function() {
var postdata = $('.subscribe form').serialize();
$.ajax({
type: 'POST',
url: 'php/sendmail.php',
data: postdata,
dataType: 'json',
success: function(json) {
if(json.valid == 0) {
$('.success-message').hide();
$('.error-message').hide();
$('.error-message').html(json.message);
$('.error-message').fadeIn();
}
else {
$('.error-message').hide();
$('.success-message').hide();
$('.subscribe form').hide();
$('.success-message').html(json.message);
$('.success-message').fadeIn();
}
}
});
return false;
});
I tried earlier with no solution, so I'm adding all my code to try and resolve this issue. I am not getting this form in my inbox, but my ajax function is working like it should. I have godaddy hosting, and am running it locally on wampp for mac. I've tried multiple different email addresses with no avail. I don't want to use php mailer. I just want this to function properly instead of what it seems to be doing which is shooting emails into outter space
html
<div class="block">
<div class="done">
<h1>Thank you! I have received your message.</h1>
</div>
<div class="form">
<form method="post" action="scripts/process.php">
<input name="name" class="text" placeholder="Name" type="text" />
<input name="email" class="text" placeholder="Email" type="text" />
<textarea name="comment" class="text textarea" placeholder="Comment"></textarea>
<input name="submit" value="Let's Go!" id="submit" type="submit" />
<div class="loading"></div>
</form></div>
</div>
<div class="clear"></div>
</div>
</div>
jquery validation and ajax
$('#submit').click(function () {
//Get the data from all the fields
var name = $('input[name=name]');
var email = $('input[name=email]');
var comment = $('textarea[name=comment]');
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailVal = email.val();
//Simple validation to make sure user entered something
//If error found, add hightlight class to the text field
if (!emailReg.test(emailVal)){
email.addClass('hightlight');
return false;
} else email.removeClass('hightlight');
if (name.val()=='') {
name.addClass('hightlight');
}else{name.removeClass('hightlight');}
if (email.val()=='') {
email.addClass('hightlight');
}else{email.removeClass('hightlight');}
if (comment.val()=='') {
comment.addClass('hightlight');
}else{email.removeClass('hightlight');}
if (name.val()=='' || email.val()=='' || comment.val()=='') {
return false;
}
//organize the data properly
var data = 'name=' + name.val() + '&email=' + email.val() + '&website='
+ website.val() + '&comment=' + encodeURIComponent(comment.val());
//disabled all the text fields
$('.text').attr('disabled','true');
//show the loading sign
$('.loading').show();
//start the ajax
$.ajax({
//this is the php file that processes the data and send mail
url: "scripts/process.php",
//GET method is used
type: "GET",
//pass the data
data: data,
//Do not cache the page
cache: false,
//success
success: function (html) {
//if process.php returned 1/true (send mail success)
if (html==1) {
//hide the form
$('.form').fadeOut('slow');
//show the success message
$('.done').fadeIn('slow');
//if process.php returned 0/false (send mail failed)
} else alert('Sorry, unexpected error. Please try again later.');
}
});
//cancel the submit button default behaviours
return false;
});
and the php which I regret to say I know very little about for now
<?php
//Retrieve form data.
//GET - user submitted data using AJAX
//POST - in case user does not support javascript, we'll use POST instead
$name = ($_GET['name']) ? $_GET['name'] : $_POST['name'];
$email = ($_GET['email']) ?$_GET['email'] : $_POST['email'];
$comment = ($_GET['comment']) ?$_GET['comment'] : $_POST['comment'];
//flag to indicate which method it uses. If POST set it to 1
if ($_POST) $post=1;
//Simple server side validation for POST data, of course,
//you should validate the email
if (!$name) $errors[count($errors)] = 'Please enter your name.';
if (!$email) $errors[count($errors)] = 'Please enter your email.';
if (!$comment) $errors[count($errors)] = 'Please enter your comment.';
//if the errors array is empty, send the mail
if (!$errors) {
//recipient - change this to your name and email
$to = 'myemail#gmail.com';
//sender
$from = $name . ' <' . $email . '>';
//subject and the html message
$subject = 'Comment from ' . $name;
$message = '
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head></head>
<body>
<table>
<tr><td>Name</td><td>' . $name . '</td></tr>
<tr><td>Email</td><td>' . $email . '</td></tr>
<tr><td>Comment</td><td>' . nl2br($comment) . '</td></tr>
</table>
</body>
</html>';
//send the mail
$result = sendmail($to, $subject, $message, $from);
//if POST was used, display the message straight away
if ($_POST) {
if ($result) echo 'Thank you! Matt has received your message.';
else echo 'Sorry, unexpected error. Please try again later';
//else if GET was used, return the boolean value so that
//ajax script can react accordingly
//1 means success, 0 means failed
} else {
echo $result;
}
//if the errors array has values
} else {
//display the errors message
for ($i=0; $i<count($errors); $i++) echo $errors[$i] . '<br/>';
echo 'Back';
exit;
}
//Simple mail function with HTML header
function sendmail($to, $subject, $message, $from) {
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= 'From: ' . $from . "\r\n";
$result = mail($to,$subject,$message,$headers);
if ($result) return 1;
else return 0;
}
?>
There are so many issues on sending PHP mails to different mail servers. For example, when I want to send email to GMail hosts I never include \r for new lines and I only go with \n. Maybe your problem is with your headers, I place my code here and see what you can get:
function send($address, $subject, $content, $from = '', $html = FALSE, $encoding = 'utf-8')
{
if(empty($address) || empty($content)) return;
$headers = "";
if($from != '')
{
$headers .= "From: {$from}\n";
$headers .= "Reply-To: {$from}\n";
}
$headers .= "To: {$address}\n";
if($html)
{
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-Type: text/html; charset={$encoding}\n";
$headers .= "Content-Transfer-Encoding: 8bit\n";
}
$headers .= "X-Priority: 1 (Highest)\n";
$headers .= "X-MSMail-Priority: High\n";
$headers .= "Importance: High\n";
$headers .= "X-Mailer: PHP/" . phpversion();
set_time_limit(30);
mail($address, $subject, $content, $headers);
}
send('myemail#myhost.com', 'title', 'content', 'myemail <myemail#myhost.com>', FALSE);
is possible to use php to reset a form without refresh?
how can i archive this?
or is possible to do it with js?
most important is do it without to refresh the page and dont add another button for this(that's because the design)
any idea?
thanks
am working with recaptcha on my form and once i submitted the information i want to send a message
this is my js code
function validateCaptcha(){
challengeField = $("input#recaptcha_challenge_field").val();
responseField = $("input#recaptcha_response_field").val();
nameField = $("input#name").val();
emailField = $("input#email").val();
phoneField =$("input#phone").val();
reasonField =$("select#reason").val();
messageField =$("textarea#message").val();
var html = $.ajax({
type: "POST",
url: "ajax.recaptcha.php",
data: "recaptcha_challenge_field=" + challengeField + "&recaptcha_response_field=" + responseField +"&name="+ nameField +"&email=" + emailField +"&phone="+ phoneField + "&reason=" + reasonField +"&message=" + messageField,
async: false
}).responseText;
if(html == "success")
{
$("#captchaStatus").html("Success. Submitting form.");
$("#thanks").html("Thank you, we going to keep in touch with you soon. ");
return false;
}
else
{
$("#captchaStatus").html("Your captcha is incorrect. Please try again");
Recaptcha.reload();
return false;
}
}
this is my php code
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$reason = $_POST['reason'];
$message = $_POST['message'] ;
if (empty($name)|| empty($email) || empty($message))
{
}
else
{
$resp = recaptcha_check_answer (PRIVATEKEY, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);
if ($resp->is_valid) {
$header = 'From: ' . $email . " \r\n";
$msg = "Sent from: " . $name . "\r\n";
$msg .= "Email: " . $email . " \r\n";
$msg .= "Phone: " . $phone . " \r\n";
$msg .= "Contact reason:" . $reason . " \r\n";
$msg .= "Message: " . $message . " \r\n";
$to = 'patricia#anetdesign.com';
$subject = 'Emailmakers contact page';
mail($to, $subject, utf8_decode($msg), $header);
?>success<?
}
else
{
die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
"(reCAPTCHA said: " . $resp->error . ")");
}
}
Well, once you sed the ajax request if the captcha fails then just reload the entire form.
Say you have only the form in myform.php and you include it in your main page, when the captcha does not match you can just reload the form. Like this:
if (html != "Success")
{
$("#divThatHoldsTheForm").html(html)
}
and in your myform.php you have only:
<form action="..." method="POST">
<!-- some inputs -->
</form>
Use the reset() function. If you have a form named frm then use can use frm.reset().
Or just write code to first get all textboxes and set its value attribute to "". this wont need to refresh your page
Using PHP mean refreshing the page (only in case of ajax) so i suggest you try to use javascript instead of php to this task