Pass html variable from Ajax to PHP - javascript

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

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.

parsererror SyntaxError: Unexpected number in JSON

I have been trying to send an Email from a contact form using Ajax.
When the mail is sent, It should return a confirmation message :
"thank you for contacting us".
Instead of displaying this message i have an error:
{"type":"success","message":"thank you for contacting us"} parsererror SyntaxError: Unexpected number in JSON at position 8
at JSON.parse (<anonymous>)
at parseJSON (jquery.js:4)
at On (jquery.js:6)
at k (jquery.js:6)
at XMLHttpRequest.r (jquery.js:6)`
Here is my PHP File sending the mail:
<?php
require_once 'phpmailer/PHPMailerAutoload.php';
$okMessage = 'thank you for contacting us';
$name = #trim(stripslashes($_POST['name']));
$email = #trim(stripslashes($_POST['email']));
$subject = #trim(stripslashes($_POST['subject']));
$message = #trim(stripslashes($_POST['message']));
$societe = #trim(stripslashes($_POST['societe']));
$num = #trim(stripslashes($_POST['num']));
$body = 'Name: ' . $name . "\n\n" . 'Entreprise: ' . $societe . "\n\n" . 'contact Tel: ' . $num . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = 'xxxxx';
$mail->Port = xx; //
$mail->CharSet = 'UTF-8';
$mail->SMTPAuth = true;
$mail->SMTPDebug = 2;
$mail->Username = "xxxx";
$mail->Password = "xxxx";
$mail->setFrom('xxxx','xxxx');
$mail->addAddress('xxxx');
$mail->Subject = $subject;
$mail->Body = $body;
$mail->send();
header('Content-type: application/json');
$status = array(
'type' => 'success',
'message' => $okMessage
);
echo json_encode($status);
die;
Here is my JS function
var form = $('#main-contact-form');
form.submit(function(event){
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
var req = $.ajax({
url: $(this).attr('action'),
type: "POST",
data: form.serialize(),
dataType : 'json',
beforeSend: function(){
form.prepend( form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>').fadeIn() );
}
});
req.done( function( data, textStatus, jqXHR ){
console.log( data, textStatus, jqXHR );
console.warn( jqXHR.responseText);
form_status.html('<p class="text-success">' + data.message + '</p>').delay(3000).fadeOut();
});
req.fail( function( jqXHR, textStatus, errorThrown ){
console.log( jqXHR.responseText, textStatus, errorThrown );
console.warn( jqXHR.responseText);
form_status.html('<p class="text-error">' + textStatus + '</p>').delay(3000).fadeOut();
});
});
Can you help me please?
I have resolved the problem.
In the network tab of my browser, i saw that the response was not only Json.
I realised that it was caused by the parameter
$mail->SMTPDebug = 2;
In fact, it returned me the whole conversation between Server and Client, before printing the response in JSON.
So I replace it by
$mail->SMTPDebug = 0;
and every thing is ok now.
Thanks for the help

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

Unable to print success message using Jquery Ajax

I'm using the Jquery Ajax to post a form data and display the success message. Everything works fine, but I'm not able to display the success message. Below is the code :
Javascript
<script>
$(document).ready(function() {
$('form').submit(function(event) { //Trigger on form submit
$('#stage').empty();
var postForm = { //Fetch form data
"name": $("#name").val(),
"element_4_1": $("#element_4_1").val(),
"element_4_2": $("#element_4_2").val(),
"element_4_3": $("#element_4_3").val(),
"email": $("#email").val(),
"input4": $("#input4").val(),
};
$.ajax({ //Process the form using $.ajax()
type : 'POST', //Method type
url : 'contact.php', //Your form processing file url
data : postForm, //Forms name
dataType : 'json',
success : function(data) {
console.log("inside success3") ;
alert(data);
$("#stage").html(data);
if (!data.success) { //If fails
if (data.errors) { //Returned if any error from process.php
$('.throw_error').fadeIn(1000).html(data.errors); //Throw relevant error
console.log("inside failure") ;
}
} else {
console.log("inside success") ;
$('#stage').fadeIn(1000).append('<p>' + data.posted + '</p>');
console.log("inside success2") ;
}
}
});
event.preventDefault(); //Prevent the default submit
});
});
</script>
PHP :
<?php
ini_set('display_errors','On');
error_reporting(E_ALL);
$errors = array();
$form_data = array();
header('Content-type: application/json');
echo json_encode($form_data);
$name=$_POST['name'];
$phone=chop($_POST['element_4_1']);
$phone.=chop($_POST['element_4_2']);
$phone.=chop($_POST['element_4_3']);
$email=chop($_POST['email']);
$message1=chop($_POST['input4']);
if ($name && $phone && $email) {
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/plain; charset=iso-8859-1\r\n";
$headers .= "From: sales#test.com \n";
$recipient= "test#test.in";
$subject="Online Enquiry ";
$message="\nName : $name\n";
$message.="\nPhone : $phone\n";
$message.="\nEmail ID : $email\n";
$message.="\nMessage : $message1\n";
//send auto-reply
$subject_reply="Thank you for contacting us";
$message_reply="Thank you for contacting us. We will get back to you shortly.";
//mail($email, $subject_reply, $message_reply, $headers);
//Send Mail
//===========
if(isset($recipient, $subject, $message, $headers)) {
error_log($message);
$form_data['status'] = 'success';
error_log($form_data['status']);
} else {
$form_data['status'] = 'error';
error_log($form_data['status']);
} ?>
HTML
<div id="stage">
</div>
How can I print the success message
You have this at the start of your php script:
echo json_encode($form_data);
where $form_data is an empty array at that time.
You should remove that and put it at the end.

Categories

Resources