简体   繁体   中英

How to access elements from a javascript array for an email sent with PHP/HTML

So I am working on a webpage that generates a javascript array from the date element in html.

That array itself works fine, and I am able to print it to the webpage by using a command like this:

document.getElementById("demo").innerHTML = week[0];

to access the "week" array generated within javascript and to paste it to an HTML span element on the webpage.

However, this is a webpage that sends emails using the data that the user inputs to the page, and while I am able to get all of the rest of the data from the user, I am unsure as to how to grab the data from this javascript array for the email.

The email is currently formatted using HTML with php variables. I thought about using a php array, but every solution I look up for that seems either to be for a different case or too complicated for me to dissect and repurpose.

So what I need is a solution like one of the following:

-The ability to copy this javascript array into a php array that I can then access for the email.

-The ability to access this javascript array within the HTML for the email

This is all contained within a php file on server (the HTML markup, the javascript functions and the php).

Thank you,

Michael

EDIT: I found this thread: Pass Javascript Array -> PHP and tried their solution with this code:

Javascript:

JSON.stringify(week);

PHP:

$datesOfWeek = json_decode($_POST['week']);

But whenever I try to access the elements of the array and print them out in the email, nothing prints out for these elements.

I'm not sure what you exactly want to achieve but if you want to send a data from js (on client) along with form data to php script (on server) you should simply serialize your array and put as value of additional (hidden) form field. In php script you can somehow deserialize a value of that field (it depends on the format of you choice)

//EDIT: Here is js script example that can you use http://jsfiddle.net/zyt2kcmv/

var myArrayToSend = ["val1", "val2"]
var arrayField = document.querySelector("[name=jsArray]");
arrayField.value = JSON.stringify(myArrayToSend)

On the server side you just need to deserialize value of $_POST["jsArray"] (use library for json or simple regex). Instead of JSON.stringify you can use myArrayToSend.join(";") and then use split method in pho to "deserialize" that string.

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