I want to allow visitors to download a PDF after they click the form submit button.
The PDF should automatically initiate the "save as dialog" after the Download button is pressed and form details sent.
I am using Javascript to send the details to a PHP form processor. I'm not an expert in either languages and I put the code together from various examples I found online.
In a nutshell, I dont know how to initiate the download automatically after form submit and I dont know whether I should use PHP or Javascript to achieve it.
Appreciate in advance any help or advise given. Thanks
This is the Javascript
$("#fhb_download_form").validator().on("submit", function (event) {
if (event.isDefaultPrevented()) {
formError1();
submitMSG1(false, "Did you fill in the form properly?");
} else {
event.preventDefault();
submitForm1();
}
});
function submitForm1(){
var fhb_fullname = $("#fhb_fullname").val();
var fhb_email = $("#fhb_email").val();
$.ajax({
type: "POST",
url: "php/fhb_form.php",
data: "fhb_fullname=" + fhb_fullname + "&fhb_email=" + fhb_email,
success : function(text){
if (text == "success"){
formSuccess1();
} else {
formError1();
submitMSG1(false,text);
}
}
});
}
function formSuccess1(){
$("#fhb_download_form")[0].reset();
submitMSG1(true, "Download Ebook")
}
function formError1(){
$("#fhb_download_form").removeClass().addClass('shake animated').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
$(this).removeClass();
});
}
function submitMSG1(valid, msg){
if(valid){
var msgClasses = "h3 text-center tada animated text-success";
} else {
var msgClasses = "h3 text-center text-danger";
}
$("#fhb_msgSubmit").removeClass().addClass(msgClasses).text(msg);
}
And this is the PHP processing code
$errorMSG = "";
if (empty($_POST["fhb_fullname"])) {
$errorMSG = "Name is required ";
} else {
$name = $_POST["fhb_fullname"];
}
if (empty($_POST["fhb_email"])) {
$errorMSG .= "Email is required ";
} else {
$email = $_POST["fhb_email"];
}
$EmailTo = "junk#zenwebcreative.com.au";
$Subject = "Ebook Downloaded by $name";
$Body = "";
$Body .= "Name:\n";
$Body .= $name;
$Body .= "\n\n";
$Body .= "Email:\n";
$Body .= $email;
$Body .= "\n\n";
$success = mail($EmailTo, $Subject, $Body, "From:".$email);
Thanks
Answer is based upon the screenshot you have shared and comments.
On the server-side, you need to remove the line which prints "success". You have to return only the file as response.
On Client-side, update your submitForm1 function as below.
function submitForm1(){
var fhb_fullname = $("#fhb_fullname").val();
var fhb_email = $("#fhb_email").val();
$.ajax({
type: "POST",
url: "php/fhb_form.php",
data: "fhb_fullname=" + fhb_fullname + "&fhb_email=" + fhb_email,
success : function(text){
// Whatever processing you need to do here
formSuccess1();
}
});
}
Please note, you have to check the function as per your functionality. I just want to highlight that you don't need to check text == "success"
Related
I am using a form-to-email.php for a contact form in my website, but I don't really understand php code.
The ready-to-use form-to-email.php file has a line "redirect to thank you page," and I have to build a thank you page for the action.
But I hope the UX could be easier like a pop-up thank you message instead of another page.
Anyone could help me to create the lines? Thank you very much!!
Below is the complete code of form-to-email.php, the line "header('Location: thank-you.html')" is the redirect path, and I'm wondering is there any way to modify the lines?
<?php
if(!isset($_POST['submit']))
{
//This page should not be accessed directly. Need to submit the form.
echo "error; you need to submit the form!";
}
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$message = $_POST['message'];
$agree = $_POST['agree'];
//Validate first
if(empty($name)||empty($visitor_email))
{
echo "Name and email are mandatory!";
exit;
}
if(IsInjected($visitor_email))
{
echo "Bad email value!";
exit;
}
$email_from = 'receiver#gmail.com';//<== update the email address
$email_subject = "letter from customer";
$email_body = "$name\n".
"Message:\n$message\nLINE ID: $line".
$to = "receiver#gmail.com";//<== update the email address
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
//Send the email!
mail($to,$email_subject,$email_body,$headers);
//done. redirect to thank-you page.
header('Location: thank-you.html');
// Function to validate against any email injection attempts
function IsInjected($str)
{
$injections = array('(\n+)',
'(\r+)',
'(\t+)',
'(%0A+)',
'(%0D+)',
'(%08+)',
'(%09+)'
);
$inject = join('|', $injections);
$inject = "/$inject/i";
if(preg_match($inject,$str))
{
return true;
}
else
{
return false;
}
}
?>
If you want to use JavaScript, you can use this code to show the message "Thank you for your message" in an alert() box:
Replace header('Location: thank-you.html') with:
echo'
<script>
window.onload = function() {
alert("Thank you for your message");
location.href = "index.php";
}
</script>
';
You can also use below AJAX script to handle it. It will not reload the page and it will give you good user experience. You must include jquery library to work.
$.ajax({
url: "ready-to-use form-to-email.php",
type: "post",
data: {id:xyz},
success: function (response) {
// you will get response from your php page (what you echo or print)
alert('Success') ;
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
Help to make a conclusion successful transmission of data. I tried in different ways, but it does not work. By clicking on the "Send" button the data is sent, but the message "Data sent successfully".
I need it to form disappeared and instead of it there was a message "Data sent successfully"
submitHandler: function(form){
var $form = $(form);
$.post('form.php', $form.serialize(), function(data){
if (!data || data.status !== 'ok') {
$form.find('input').addClass('error');
return false;
}
forms.fadeOut('slow', function(){
$('.form--success').fadeIn('fast');
});
}, 'json');
return false;
}
});
form.php
if(isset($_POST['submit'])) {
$to = "example#example.com";
$subject = "Contact Form";
$phone = $_POST['phone'];
$mail = $_POST['mail'];
$headers = "From: $phone<$mail>\r\n";
$body = "From: $phone<$mail>\r\n Phone Number: $phone\n E-Mail: $mail\n";
mail($to, $subject, $body, $headers);
exit();
}
http://37.230.210.96/ - testing site
You're not targeting the right element to fade out. You have:
var form = $(form);
To fade that out you would use this:
form.fadeOut('slow', function(){
$('.form--success').fadeIn('fast');
});
forms != form
Can anybody help me with this? I am not highly proficient in coding but know enough to get by. The issue is that the form can be filled out but in the telephone number field it won't accept spaces and 2) when it is filled out properly it does not return a value of "submitted".
Any help is greatly appreciated.....
$("#ajax-contact-form").submit(function() {
var str = $(this).serialize();
var href = location.href.replace(/dark\/|video\/|slider\/|contact\.html/g,'');
$.ajax({
type: "POST",
url: href + "contact_form/contact_process.php",
data: str,
success: function(msg) {
// Message Sent - Show the 'Thank You' message and hide the form
if(msg == 'OK') {
$(this).addClass('success').find('span:eq(1)').html('success');
} else {
$(this).addClass('error').find('span:eq(1)').html('error');
}
}
});
return false;
});
and the PHP code
<?php
include dirname(dirname(__FILE__)).'/mail.php';
error_reporting (E_ALL ^ E_NOTICE);
$post = (!empty($_POST)) ? true : false;
if($post){
$name = stripslashes($_POST['name']);
$email = trim($_POST['email']);
$phone = stripslashes($_POST['phone']);
$message = stripslashes($_POST['message']);
$mail = mail(CONTACT_FORM, $phone, $message,
"From: ".$name." <".$email.">\r\n"
."Reply-To: ".$email."\r\n"
."X-Mailer: PHP/" . phpversion());
if($mail){
echo 'OK';
}
}
?>
your data is the wrong syntax you need to define it and then put the key in it i.e.
data: {str: str},
http://api.jquery.com/jQuery.ajax/
The script below helps with processing of a form that request number and name values, and than sends it to process.php and also displays a confirmation and hides the button that would fired the modal to the form so user cannot retry to fill the form.
Script to handle pass data to process.php
$(document).ready(function () {
function successHandler(){
console.log('Success');
$("#thanks").html(msg);
$('#form-content').modal('hide');
}
function errorHandler(){
console.log('Error');
alert("Error");
}
var nameval = $('#name').val();
var numberval = $('#number').val();
$("form#contact").submit(function(){
$.ajax({
type: "POST",
url: "process.php",
data: {
name: nameval,
number: numberval,
submit: true
},
success: function(msg){
$("#thanks").html(msg);
$('#form-content').modal('hide');
return false;
},
error: function(){
alert("Error");
return false;
}
});
return false;
});
});
The whole action does generate an email with HTML from the process.php script but does not include the data that was captured from the form, I believe there is a error within this script as I cannot find anything on the form or process.php that is using PHPMail() doing anything wrong.
Could you help?
Update
<?php
if (isset($_POST['submit'])) {
$name = ($_POST['name']);
$number = ($_POST['number']);
echo "<span class=\"alert alert-success\">THANKS! SUBMITTED</span>";
$to = "EMAIL BLANKED";
$subject = "Alert!";
$message = "name: $name number: $number";
// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// More headers
$headers .= 'From: <email blank>' . "\r\n";
mail($to,$subject,$message,$headers);
}
else { echo '<div class="alert alert-error">Error</div>' ; }
?>
You should put this two lines:
var nameval = $('#name').val();
var numberval = $('#number').val();
inside the submit function like this
$("form#contact").submit(function(){
var nameval = $('#name').val();
var numberval = $('#number').val();
because if you set the values of the variables before the submission of the form the inputs will most likely be empty.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm getting no errors, but when submit is hit, form is cleared, email is sent but no redirection happens. I have also tried to redirect using script, with now luck.
Form Page
<script>
$(function(){
$('#form3').submit(function(e){
//Prevent the default form action
e.preventDefault();
function validateEmail($email2) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if( !emailReg.test( $email2 ) ) {
return false;
} else {
return true;
}
}
var thisForm = $(this);
$("#emailError2").hide();
$("#firstnameError2").hide();
$("#lastnameError2").hide();
$("#cityError2").hide();
$("#phoneError2").hide();
$("#countryError2").hide();
$("#messageError2").hide();
var errors = false;
var email2 = $("input[id='email2']").val();
var firstname2 = $("input[id='firstnam2e']").val();
var lastname2 = $("input[id='lastname2']").val();
var phone2 = $("input[id='phone2']").val();
var business = $("input[id='business']").val();
var nbusiness = $("input[id='nbusiness']").val();
var message2 = $("textarea[id='message2']").val();
if(( !validateEmail(email2)) || (email2=="")) {
errors = true;
$("#emailError2").fadeIn();
return;
}
if(firstname2=="") {
errors = true;
$("#firstnameError2").fadeIn();
return;
}
if(lastname2=="") {
errors = true;
$("#lastnameError2").fadeIn();
return;
}
if(business=="") {
errors = true;
$("#cityError2").fadeIn();
return;
}
if(phone2=="") {
errors = true;
$("#phoneError2").fadeIn();
return;
}
if(errors == false){
//Hide the form
$(this).fadeOut(function(){
//Display the "loading" message
$("#loading2").fadeIn(function(){
//Post the form to the send script
$.ajax({
type: 'POST',
url: thisForm.attr("action"),
data: thisForm.serialize(),
//Wait for a successful response
success: function(data){
//Hide the "loading" message
$("#loading2").fadeOut(function(){
//Display the "success" message
$("#success2").text(data).fadeIn();
});
}
});
});
});
}
})
});
I have a whole whack form inputs here, followed by:
<div class="contactRow" style="height:160px; margin-top:91px;">
<textarea name='message2' id="message2" rows="8" cols="38" placeholder="Comments"></textarea> </div>
<div class="contactRow"><center><input type="checkbox" name="I-agree" required>I agree to theTerms and Conditons</input> </center><div class="contactSubmit"><input type='submit' value="Submit"></div></div>
seperate.php page to send off email
<?php
if (isset($_POST['email2']))
//if "email" is filled out, send email
{
//send email
$email2 = $_POST['email2'] ;
$firstname2 = $_POST['firstname2'] ;
$lastname2 = $_POST['lastname2'] ;
$nbusiness = $_POST['nbusiness'] ;
$phone2 = $_POST['phone2'] ;
$business = $_POST['business'] ;
$message2 = $_POST['message2'] ;
$sizeof2 = $_POST['sizeof2'] ;
$whattype2 = $_POST['whattype2'] ;
$whoare2 = $_POST['whoare2'] ;
$wheredid2 = $_POST['wheredid2'] ;
$comment2 = "$message2 \n\n $firstname2 \n $lastname2 \n $phone2 \n $business \n $nbusiness \n $email2 \n $sizeof2 \n $whattype2 \n $whoare2 \n $wheredid2 \n\n";
/*$headers = 'From: ------#-----.com' . "\r\n" .
'Reply-To: ------a#s-----.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();*/
$headers2 = 'From: '.$email2."\r\n" .
'Reply-To: '.$email2."\r\n" .
'X-Mailer: PHP/' . phpversion();
//-----#-----.com
mail("------#-----.ca", "-------------: ".$firstname2, $comment2, $headers2);
header ('Location: thankyou.html');
exit ();
}else{
echo "There was a problem with the registration";
}
?>
Since your form submit results in an AJAX request, you should redirect upon successful completion of that request.
$.ajax({
type: 'POST',
...
// Wait for a successful response
success: function(data) {
...
window.location.href = "thankyou.html"; // <-- REDIRECT HERE
}
});
You can also use window.location.replace("thankyou.html"); if you do not wish put the originating page in the session history.
In you php you should probably replace the header ('Location: thankyou.html'); with code returning a message or whatever you want to the AJAX request (e.g. echo "Success!";).