Send Email using JavaScript & PHP - javascript

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

Related

I keep getting a 400 (Bad Request) when submitting a WordPress form using the Fetch API

I am working on a WordPress site and I am trying to convert my jQuery code to vanilla JavaScript (mostly as a learning experience, but also so I don't have to rely on jQuery). The goal is once the form is submitted, instead of going to a thank you page or something else, simply display an overlay over the form saying "Thank you for your message". Again, everything works fine with jQuery/AJAX, but I want to try and get it working with plain JavaScript as well.
Here is the working jQuery code:
jQuery('#myContactForm').on('submit', function () {
var formData = jQuery(this).serializeArray();
formData.push({
name: 'security',
value: ajaxNonce
});
jQuery.ajax({
type: 'POST',
url: ajaxUrl,
data: formData
});
jQuery('.form-overlay').addClass('visible');
return false;
});
And here is the working code from functions.php:
<?php
function javascript_variables() { ?>
<script type="text/javascript">
var ajaxUrl = '<?php echo admin_url('admin-ajax.php'); ?>';
var ajaxNonce = '<?php echo wp_create_nonce('secure_nonce_name'); ?>';
</script>
<?php
}
add_action('wp_head', 'javascript_variables');
add_action('wp_ajax_send_form', 'send_form');
add_action('wp_ajax_nopriv_send_form', 'send_form');
function send_form() {
check_ajax_referer('secure_nonce_name', 'security');
$to = 'myemailaddressgoeshere#gmail.com';
$subject = $_POST['subject'];
$body = 'From: ' . $_POST['full_name'] . '<br />';
$body .= 'Email: ' . $_POST['email'] . '<br />';
$body .= 'Phone: ' . $_POST['phone'] . '<br />';
$body .= 'Message: ' . $_POST['message'] . '<br />';
$headers = array('Content-Type: text/html; charset=UTF-8');
wp_mail($to, $subject, $body, $headers);
wp_die();
}
And finally, here is the relevant input inside the form:
<input class="form-inputs" type="hidden" name="action" value="send_form" />
Here is what I came up with when trying to use the Fetch API instead of jQuery:
// handle form submission
const formSubmissionHandler = () => {
const form = document.getElementById('myContactForm');
const formOverlay = document.querySelector('.form-overlay');
const formInputs = Array.from(document.querySelectorAll('.form-inputs'));
const formData = [];
form.addEventListener('submit', (e) => {
e.preventDefault();
formInputs.forEach((input) => {
if (!input.name || !input.value) {
return;
}
formData.push({
name: input.name,
value: input.value,
});
});
formData.push({
name: 'security',
value: ajaxNonce,
});
const fetchOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(formData),
};
// send post request
fetch(ajaxUrl, fetchOptions)
.then((res) => res.json())
.then((res) => console.log(res))
.catch((err) => console.error(err));
formOverlay.classList.add('visible');
});
};
document.addEventListener('DOMContentLoaded', formSubmissionHandler);
I've come across the FormData() constructor from searching, not sure where/if I would use that here?
And here is what I wrote in my functions.php file:
function send_form() {
check_ajax_referer('secure_nonce_name', 'security');
$to = 'myemailaddressgoeshere#gmail.com';
$subject = $_POST['subject'];
$json_input = json_decode(file_get_contents('php://input'), true);
$body = '';
foreach ($json_input as $key => $value) {
$body = 'From: ' . $value['full_name'] . '<br />';
$body .= 'Email: ' . $value['email'] . '<br />';
$body .= 'Phone: ' . $value['phone'] . '<br />';
$body .= 'Message: ' . $value['message'] . '<br />';
}
$headers = array('Content-Type: text/html; charset=UTF-8');
wp_mail($to, $subject, $body, $headers);
wp_die();
}
I am new to all this so if someone could help me out it would be much appreciated. I think my issue is how I am parsing the JSON data in functions.php. Or could I simply not format the data the same in vanilla JS as it's done in jQuery? Thank you!
I know it is probably a bit late for me to post this but incase somebody in future runs into this, here is the deal:
const fetchOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(formData),
};
here, you are making a json string to pass to the destination URL but you have to remember, Wordpress's ajax parser can't understand data being sent to it as raw json.
$json_input = json_decode(file_get_contents('php://input'), true);
here, you're turning the raw input that you received into an array, but before this, all Wordpress got was a piece of data which is a simple string. So, it doesn't know how to deal with it and what user-defined hook and actions should be fired to validate this.
add_action('wp_ajax_send_form', 'send_form');
add_action('wp_ajax_nopriv_send_form', 'send_form');
here, you are telling wordpress to expect some request with the 'action' name of 'send_form' and if you got it, pass it to a function named 'send_form'. Wordpress however is not recieving that request with the name 'action'. Hence the error.
The fix, however, is quite simple, just add this request name as a GET to the url you're sending the raw data to and clear it up for wordpress:
var ajaxUrl = '<?php echo admin_url('admin-ajax.php'); ?>?action=send_for';
or, the version I prefer:
// send post request
fetch(ajaxUrl + '?action=send_form', fetchOptions)
.then((res) => res.json())
.then((res) => console.log(res))
.catch((err) => console.error(err));
and done!
I think once you star to work with fetch() and WP, at least for now (untill Wordpress figures out a way), this could come handy.

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 :)

Pass html variable from Ajax to PHP

I am trying to use this code to pass via POST a variable containing HTML
var data = {
message: $('#mydiv').html()
};
jQuery.ajax({
type: 'POST',
data: data,
url: '/myurl?action=send_email',
success: function( response ) { }
});
In PHP, I retrieve the data and I send an Email using the data content
$message = "Hello<br>" . $_POST['message'] . "<br>Bye Bye";
$mail = mail($email, $subject, nl2br($message), $headers);
The HTML within the email that I receive is badly formatted:
<img width="\"70\"" height="\"87\"" alt="\"D_6928_antiqueoak_vapor\"">
Can someone tell me why and if there is a solution? Thank you a lot
Try this method using encodeURIComponent()
var data = 'message='+$('#mydiv').html();
jQuery.ajax({
type: 'POST',
data: encodeVars(data),
url: '/myurl?action=send_email',
success: function( response ) { }
});
function encodeVars(vars){
return vars.map(function (cell) {
var res = cell.split('=');
return res[0] + '=' + encodeURIComponent(res[1]);
}) ;
}
Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
I solved in that way. Javascript
var data = {
message: $('#mydiv').html()
};
jQuery.ajax({
type: 'POST',
data: data.replace(/&/g, "&")
.replace(/"/g, """)
.replace(/'/g, "'"),
url: '/myurl?action=send_email',
success: function( response ) { }
});
PHP
$message = preg_replace('/&/', '&', $_POST['message']);
$message = preg_replace('/"/', '"', $message);
$message = preg_replace('/'/', "'", $message);
$message = "Hello<br>" . $message . "<br>Bye Bye";
$mail = mail($email, $subject, nl2br($message), $headers);

send textbox variables via php form

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

jquery js post variable set and get for post

I need to send some parameters from a php page to another to post email dynamically,
if I send the value as hardcoded is ok, but if i send the value on a textfield, it doesnt work,
here the code
page that request post of mail
<script>
$otroYa = other.val();
console.log (other.val()); //shows value ok of this var!
$.post( "send-mail-parklane-suscrib.php" , {otro: "ss9", otro2: $otroYa });
</script>
so,
otro2 = $otroYa
doesnt get set? , but hardcoding otro, is ok
php page called to perform post
<html>
<head><title>PHP Mail Sender</title></head>
<body>
<?php
session_start();
echo("chamb");
$to = 'juanma#gmail.com';
$from = 'bot#prklanefinancial.com.au';
$subject = 'Prklane Financial Subscribe';
$headers = 'From: bot#prklanefinancial.com.au' . "\r\n".
'Reply-To: test#abc.com'. "\r\n".
'Return-Path: test#abc.com' . "\r\n".
'X-Mailer: PHP/' . phpversion();
$message = "SS9 tkt ss9!!!";
$name=$_POST['otro2'];
mail($to, $subject, $name, $headers, "-f $from");
?>
</body>
</html>
so if I send my mail with the value
$name=$_POST['otro2'];
is empty
but using the hardcoded
$name=$_POST['otro'];
is ok
how to set the var?
thanks!
You mixed up PHP & JavaScript .
Instead of
$otroYa = other.val();
It should be:
var otroYa = other.val();
and the jquery post request should be:
$.post( "send-mail-parklane-suscrib.php" , {otro: "ss9", otro2: otroYa });

Categories

Resources