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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.