简体   繁体   中英

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

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