简体   繁体   中英

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="\&quot;70\&quot;" height="\&quot;87\&quot;" alt="\&quot;D_6928_antiqueoak_vapor\&quot;">

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, "&amp;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#039;"),
    url: '/myurl?action=send_email',
    success: function( response ) { }
});

PHP

$message = preg_replace('/&amp;/', '&', $_POST['message']);
$message = preg_replace('/&quot;/', '"', $message);
$message = preg_replace('/&#039;/', "'", $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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM