0

I'm struggling trying to convert my JavaScript array of emails into a PHP array which I can then send an email back to using my localhost.

I have an input field in my html that is populated by the user (one at a time) which uses .push in JavaScript to put them into the array. I have tried to use fetch to then convert this array into PHP, which I can then then use to send an email back to the email addresses using PHPMailer.

The emails aren't appearing in my console as an array, but will do if I change the content type to "Content-Type": "application/x-www-form-urlencoded". However, the emails still aren't being sent this way.

This is only for a small uni project, that's why I am only concerned about sending the emails through my localhost as I won't be hosting the project anywhere.

HTML:

<input type="text" id="names" placeholder="Name" />
<input type="text" id="emails" placeholder="Email address" />
<input type="button" onclick="addTo()" value="Add" />

<input type="button" id="done-button" onclick="completed()" value="Done" />

JavaScript:

var names = [];
var emails = [];
var allNumbers = [];

function addTo() {
    names.push(document.getElementById("names").value);
    document.getElementById("names").value = "";
    emails.push(document.getElementById("emails").value);
    document.getElementById("emails").value = ""; 
}

function completed() {
    var numbers = names.length;
        for (var i = 1; i <= numbers; i++) {
            allNumbers.push(i);
        }

    fetch("http://localhost:8888/fetchme.php", {
        method: "POST", // *GET, POST, PUT, DELETE, etc.
        mode: "no-cors", // no-cors, cors, *same-origin
        cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
        credentials: "same-origin", // include, *same-origin, omit
        headers: {
            "Content-Type": "application/json"
        },
        redirect: "follow", // manual, *follow, error
        referrer: "no-referrer", // no-referrer, *client
        body: emails // body data type must match "Content-Type" header
    }).then((response) => {console.log(response)}); // parses response to console
}

PHP:

<?php 
var_dump($_POST);

use PHPMailer\PHPMailer\PHPMailer;
require '../vendor/autoload.php';
$mail = new PHPMailer;
//Tell PHPMailer to use SMTP
$mail->isSMTP();
$mail->SMTPDebug = 2;
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = "example@gmail.com";
$mail->Password = "password";
$mail->setFrom('example@gmail.com', 'Example');

$emails = json_decode($_POST);

if (isset($emails)) {
    foreach ($emails as $email) {
        $mail->addAddress($email);
        $mail->Subject = 'Your Results';
        //Read an HTML message body from an external file, convert referenced images to embedded,
        //convert HTML into a basic plain-text alternative body
        //$mail->msgHTML(file_get_contents('index.html'), __DIR__);
        $mail->Body = 'Hello, this is my message.';
        $mail->AltBody = 'This is a plain-text message body';
        if (!$mail->send()) {
            echo "Mailer Error: " . $mail->ErrorInfo;
        } else {
            echo "Message sent!";
        }
    }
}
?>
  • `exit` stops anything after it from running. – Jonnix Dec 31 '18 at 15:47
  • If you're posting the data as json in the body, you might need to fetch it using `$json = file_get_contents('php://input');`. You can read more about the difference [here](https://stackoverflow.com/questions/8893574/php-php-input-vs-post) – M. Eriksson Dec 31 '18 at 15:50
  • `$emails = json_decode($_POST);` makes no sense. See @MagnusEriksson comment for the usual way. – Jonnix Dec 31 '18 at 15:51

2 Answers2

0

Using fetch() with an array as body doesn't send a JSON string. What's being sent to the server is a comma separated list of the email addresses. Anyway, PHP won't put them into $_POST because the body is not a valid query string.

First, you should use JSON.stringify() to convert the emails array to a JSON string. Then, in PHP, you could read the request body with http_get_request_body().

Or, you can build the query string to set it as the body of the request, and then you'll be able to use $_POST normally.

Gabriel
  • 2,170
  • 1
  • 17
  • 20
0

Try to use class instead of id for name and emails, then try to get value in javascript itself with console log if you are getting value in javascript before passing it to PHP

shivanisdev
  • 687
  • 6
  • 16