send textbox variables via php form - javascript

I have created a form using Ninja Forms on my WordPress website. I have one long form, which I've divided into tabs. When the user clicks the first button to continue, I want to send an email with specific fields. The issue is that my variables don't show up in my email. I'm receiving blank emails.
I've tried a number of things including ajax and a separate sendme.php. Since I'm using Wordpress, I decided to use the wp_mail function.
Here's my code. The variables work in my jquery alerts, but still aren't passed to my email.
I included this in my header.
$("#cont-btn").on('click', function (e) {
e.preventDefault();
var name = $("#ninja_forms_field_30").val();
var company = $("#ninja_forms_field_76").val();
var title = $("#ninja_forms_field_75").val();
var email = $("#ninja_forms_field_33").val();
var phone = $("#ninja_forms_field_32").val();
$.ajax({
type: "POST",
url: "sendme.php",
data:{ name: name, company: company, title: title, email: email, phone: phone },
success: function(data){
console.log(data);
}
})
});
And this is the basis of my sendme.php
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$company = $_POST['company'];
$phone = $_POST['phone'];
$to = 'me#email.co';
$subject = 'Enterprise Quote (PT1)';
$message = 'Email: ' .$company ;
$headers = '';
mail($to, $subject, $message) or die('Error sending Mail'); //This method sends the mail.
?>
A few things:
I don't want to validate the form.
I don't want to submit the form.
I want the user to stay on page.
Any help would be greatly appreciated. Thanks.

You cannot mix PHP and Javascript in this fashion, you have to separate you php and trigger it using AJAX requests.
So first put the php code in a separate file:
send.php
<?php
$headers = 'From: Me Myself <me#example.net>';
$message = $_POST['et_contact_message'];
$message .= '
Name: ' . $_POST['ninja_forms_field_30'];
$message .= '
Company: ' . $_POST['ninja_forms_field_76'];
$message .= '
Email: ' . $_POST['ninja_forms_field_33'];
$message .= '
Phone: ' . $_POST['ninja_forms_field_32'];
wp_mail( 'myemail#company.com', 'Enterprise Get a Quote (PT1)', $message, $headers );
?>
Then in your JS (jQuery)
$("#cont-btn").on('click', function (e) {
e.preventDefault();
var formData = $('#the-form').serialize(); //replace 'the-form' with your form id
$.post('/link/to/send.php', formData, function(res){
});
});

Related

How do I prompt my alert to the user with a php file?

I want to make a contact form using php and javascript and I'm having a hard time with the alert() function. What I want to do, is inform the user of what's happening in the back end. I noticed that my "echo" functions get prompted into the console and I want to make them visible as an alert() function.
Here is my javascript:
$(document).ready(function() {
$("#submit").click(function() {
console.log("button clicked");
var name = $("#name").val();
var adresse = $("#adresse").val();
var telephone = $("#telephone").val();
var email = $("#email").val();
var project_place = $("#project_place").val();
var message = $("#message").val();
$("#returnmessage").empty(); // To empty previous error/success message.
// Checking for blank fields.
if (name == '' || email == '' || telephone == '' || message == '') {
alert("Please fill out the required fields.");
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post("includes/mail.php", {
name1: name,
adresse1: adresse,
telephone1: telephone,
email1: email,
project_place1: project_place,
message1: message
}, function(data) {
console.log(data);
$("#returnmessage").append(data); // Append returned message to message paragraph.
if (data == "Email sent.") {
$("#frmContact")[0].reset(); // To reset form fields on success.
alert("Email sent.");
}
});
}
});
});
and here's my php:
<?php
// Fetching Values from URL.
$name = $_POST['name1'];
$adresse = $_POST['adresse1'];
$telephone = $_POST['telephone1'];
$email = $_POST['email1'];
$lieu_du_projet = $_POST['lieu_du_projet1'];
$message = $_POST['message1'];
$email = filter_var($email, FILTER_SANITIZE_EMAIL); // Sanitizing E-mail.
// After sanitization Validation is performed
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
if (!preg_match("/^[0-9]{10}$/", $telephone)) {
echo "Please, enter a valid number";
} else {
$subject = $name;
// To send HTML mail, the Content-type header must be set.
$headers = 'MIME-Version: 1.0' . "rn";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "rn";
$headers .= 'From:' . $email. "rn"; // Sender's Email
$headers .= 'Cc:' . $email. "rn"; // Carbon copy to Sender
$template = 'Hi ' . $nom . ","
. "\n\nThank you form contacting us,"
. "\nName: " . $name
. "\nAdresse: " . $adresse
. "\nTelephone: " . $telephone
. "\nEmail: " . $email
. "\nProject Place: " . $project_place
. "\nMessage: " . $message
. "\nThis is a confirmation email. "
. "\nWe'll get back to you as soon as possible";
$sendmessage = $template ;
// Message lines should not exceed 70 characters (PHP rule), so wrap it.
$sendmessage = wordwrap($sendmessage, 70);
// Send mail by PHP Mail Function.
mail("my#email.com", $subject, $sendmessage, $headers);
echo "Email sent.";
}
} else {
echo "Email invalid.";
}
?>
Any help would be appreciated, thanks a lot!

Equal sign in javascript mailto url getting parsed on Android

I have a web app that sends a URL link in the body of the email from a button onclick="email();". The url is a php page with .php?id= and everything after equal sign is getting truncated when sent from an Android device.
I have tried encoding the URL but nothing is working...
I know the mailto tag uses the = sign as a parsing character...but still cannot figure this out.
Here is code.
function email() {
window.location.href = "mailto:?subject=LIVE link!&body=Here is a link for a LIVE demo!%0D%0Awww.domain.ca/scores/" + sport + "php%3Fid%3d" + id +"%0D%0A%0D%0AThanks";
}
Any suggestions or experience in this?
Works fine on all other platforms (iOS, Windows etc)
Turns out is was specific to Outlook app on Android device.
This is from one of my sites..
<?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['mail'];
$message = $_POST['appointment'];
//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 = 'Client';//<== update the email address
$email_subject = "Booking an appointment";
$email_body = "You have received a new message from the user $name.\n"."Here
is the message:\n $message";
$to = "somebody#hotmail.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: aboutUs.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;
}
}
?>

Send Email using JavaScript & PHP

I am trying to send an email to myself using Ajax and PHP. The following seems to be sending the email but doesn't seem to pass the variables into PHP from Javascript.
JavaScript
var aaa = $('#aaa').val();
var bbb = $('#bbb').val();
var data = 'A: ' + aaa + ' B: ' + bbb;
$.ajax({
type: "POST",
url: "sendMail.php",
data: data,
success: function(){
alert("Email Sent");
}
});
PHP Code:
<?php
$subject = $_POST['data'];
mail("test#gmail.com", $subject, "", "From: info#test.com") or die("Error!");
?>
Could anyone please advise on how to fix this?
As pointed out in the comments your data variable in js is formatted the wrong way (it needs to be an object! ), you can use this one liner after defining data to convert it into the right format, as data:
data = { data: data };
this would make you not have to adjust the PHP code and populate the 'data' index in your $_POST superglobal with the string.
$to="123#gmail.com";
$subject="Work Done by ";
$subject .= $myusername;
$headers = 'From: 456#gmail.com' . "\r\n" .'X-Mailer: PHP/' . phpversion();
$messages ="test" ;
$messages .="test1" ;
$ret = mail($to, $subject, $messages, $headers);

PHP form handler with jQuery script duplicating emails

I have a php function handling the results of a form delivered from a jQuery script, as the form content is also delivered to a Workbooks CRM url to be added to records there.
All works fine, except the email is sent 3 times. The button clicked is not inside the form, and the 'send' value for isset($_POST) is delivered from a hidden form field in the form.
I've tried:
Adding flags, both in PHP and in the jQuery.
Adding alerts in the jQuery.
Adding exit("sent"); after the mail() function.
The alert() experiment appeared to indicate the jQuery wasn't the issue, but flags seemed to indicate the same in the PHP!
Here's the jQuery:
$(document).ready(function () {
$("#test-vf-button1").click(function (event) {
event.preventDefault();
// Field values as array
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
var formData = $("#wb_form").serialize();
var url = $(location).attr('hostname');
var pathname = $(location).attr('pathname');
var pageUrl = url + pathname;
console.log(pageUrl);
$("#validate-message").empty();
$("#confirm-message").empty();
if (name == '' || email == '' || message == '') {
$("#validate-message").append(" Fill in required fields");
} else {
// Returns successful data submission message when the entered information is stored in database.
$.ajax({
type: 'POST',
url: "http://visual-factory.co.uk/",
data: formData,
success: function () {
$.ajax({
type: 'POST',
url: "https://secure.workbooks.com/crm/web_leads",
crossDomain: true,
data: formData,
dataType: 'text',
success: function () {
PHP handling function:
function vf_deliver_mail() {
// if the submit button is clicked, send the email
if ( isset( $_POST['send'] ) ) {
// sanitize form values
$title = sanitize_text_field( $_POST['person_lead_party']['person_personal_title'] );
$name = sanitize_text_field( $_POST['person_lead_party']['name'] );
$jobrole = sanitize_text_field( $_POST['person_lead_party']['person_job_role'] );
$email = sanitize_text_field( $_POST['org_lead_party']['main_location']['email']);
$phone = sanitize_text_field( $_POST['org_lead_party']['main_location']['telephone'] );
$company = sanitize_text_field( $_POST['org_lead_party']['name'] );
$country = sanitize_text_field( $_POST['org_lead_party']['main_location']['country'] );
$messagecontent = esc_textarea( $_POST['vf-message'] );
$message = "<p>Title: ".$title."</p>";
$message .= "<p>Name of lead is: ".$name."</p>";
$message .= "<p>Job Role: ".$jobrole."</p>";
$message .= "<p>Email is: ".$email."</p>";
$message .= "<p>Phone is: ".$phone."</p>";
$message .= "<p>Company is: ".$company."</p>";
$message .= "<p>Country is: ".$country."</p>";
$message .= "<p>Message: ".$messagecontent.".</p>";
// get the blog administrator's email address
$to = get_option( 'admin_email' );
$subject = "Form response";
$headers = "From: $name <$email>" . "\r\n";
mail( $to, $subject, $message, $headers ) ;
}
}

Why does a simple ajax call to php exhibit such strange behavior?

I am making a call to a jQuery Mobile form to a simple PHP mailing file. I have tested the PHP file using the same data I am passing from the ajax call, which works just fine. However, when using ajax, the email is not sent and the address bar contains the query string. I really need more sets of eyes looking a this, since my mine seem permanently crossed.
Form Excerpt
<form id="hipaa-form" name="hipaa-form" autocomplete="on" data-ajax="false">
<p data-role="fieldcontain">
<label for="name">Name:<span class="smallred">*</span></label>
<input type="text" name="name" id="name" autofocus required placeholder="Full Name">
</p>
<p>
<input type="submit" name="send" id="send" style="cursor:pointer" value="Submit">
</p>
</form>
JavaScript
$('#hipaa-form').on('submit', function (e) {
var data = $(this).serialize();
$.ajax({
type: "GET",
url: email.php,
data: data,
dataType: "text",
success: function (result) { alert(result); },
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert("Error: " + +err.Message)
}
});
});
Note the data variable is set correctly, and is the string that winds up in the address bar. The alert from the success function displays the entire web page, but again the email is not sent. I tried setting custom error handlers in PHP, but they were no help at all.
PHP
$body = "Full Name: " . $_GET["name"] . "\r\n";
$body = $body . "email: " . $_GET["email"] . "\r\n";
$body = $body . "Phone: " . $_GET["phone"] . "\r\n";
$body = $body . "website: " . $_GET["Website-URL"] . "\r\n";
$body = $body . "app. type: " . $_GET["pgm-type"] . "\r\n";
$body = $body . "uses DB: " . $_GET["uses-db"] . "\r\n";
$body = $body . "saves data: " . $_GET["stores-patient-data"] . "\r\n";
$body = $body . "db vendor: " . $_GET["database-vendor"] . "\r\n";
if (isset($_GET["db-other"]))
$body = $body . "other db: " . $_GET["db-other"] . "\r\n";
$to = "contact.us#bunkerhill.com";
$subject = "HIPAA Form Submission";
mail($to, $subject, $body, "From: contact.us#text.bunkerhill.com");
echo "Form Submitted"
?>
My test site is : http://test.bunkerhill.com/
TIA
You need to block the form from being submitted with preventDefault();
$('#hipaa-form').on('submit', function (e) {
e.preventDefault();
...
}
Your ajax request should use querystring parameters with a GET or, change to type: "POST" and adjust your PHP to use $_POST
Example:
type: "GET",
url: "page.php?foo=x&bar=y"
Or
type: "POST",
url: "page.php",
data: data
Lastly, I'm a little worried about this example including HIPAA information. You might want to consider an approach where you store the information in a secure location and simply send an email that says, "Hey a new message is available. Click here to authenticate against our secure system to read it." Not that there is anything absolutely wrong with your approach but it feels like there is additional HIPAA related liabilities to consider.
url param in your Ajax definition should be 'email.php' in quotes, so change
url: email.php
to
url: 'email.php'
Without that it's just sending a call to http://test.bunkerhill.com/ and your PHP code sending email is never invoked at all :)

Categories

Resources