Send a Javascript array in a mail - javascript

I have an HTML form to retrieve some options from checkboxes:
<form action="" method="post" id="menuform" name="menuform">
<fieldset>
<legend>Select a Menu</legend>
<label>
<input type="radio" name="selectedmenu" checked value="menu01" ape-qty='8' ent-qty='1' pes-qty='1' sor-qty='1' car-qty='1' pos-qty='1' data-price='95' />
<span>First Item</span>
</label>
...(more)...
</fieldset>
<fieldset>
<legend id='aperitivosPrompt'>Elegir Aperitivos</legend>
<label>
<input type='checkbox' name='aperitivos' value="1" />
<span>Item 1</span>
</label>
<label>
<input type='checkbox' name='aperitivos' value="2" />
<span>Item 2</span>
</label>
<label>
<input type='checkbox' name='aperitivos' value="3" />
<span>Item 3</span>
</label>
...(more)...
</fieldset>
<fieldset>
<input type="submit" value="Enviar" />
</fieldset>
</form>
Then I send this variables to a JavaScript file and I save all checkboxes options in multiple arrays
var menuform = document.getElementById('menuform'),
radios = document.getElementsByName('selectedmenu'),
aperitivos = document.getElementsByName('aperitivos'),
aperitivosPrompt = document.getElementById('aperitivosPrompt'),
totalPrice = document.getElementById('totalPrice'),
result = document.getElementById('result'),
aperitivosAllowed = 0,
currentSelectionAperitivos = [],
currency = '€';
function handleAperitivos(e) {
var count = getSelectedCountApe();
if (count > aperitivosAllowed) {
resetSelectApe();
} else {
currentSelectionAperitivos = getSelectedValuesApe();
}
}
...(more)...
function getSelectedCountApe() {
var count = 0;
for (var i = 0; i < aperitivos.length; i++) {
if (aperitivos[i].checked) count++;
}
return count;
}
...(more)...
So, how can I send these arrays named currentSelectionAperitivos = [] in an email? I want that after user selects all his options, I receive an email in my inbox with his selected options.
I think that I must connect this form and JS file with a PHP function and send emails from there. Anyway, how can I do this?
-EDITED-
I tried a solution with JSON:
for (var i = 0; i < aperitivos.length; i++) {
var item = {
"valor": i,
"etiqueta": aperitivos[i].value
};
currentSelectionAperitivos.push(item);
}
currentJSON = JSON.stringify({currentSelectionAperitivos:currentSelectionAperitivos});
console.log(currentJSON);
So now I get in browser console all "values" from fields <input> of the HTML form. But not only CHECKED values and anyway, what I need now is to get this JSON.stringify and send it by mail with PHP.

Write a PHP script to send the email, change the form action to post on this script.
Attention: this is untested.
Change your form to:
<form action="mail.php"...>
</form>
Create mail.php like
<?php
ob_start();
var_dump($_POST);
$result = ob_get_clean();
mail ( 'your#email.com' , 'subject' , $result);
?>
Otherwise you could use JSON.stringify and an API to send the E-Mail with JS.

I found a good solution for my needs. I get all 'checked' values and I create an email with theme.
So, HTML form:
<html>
<head>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.9.1.js'></script>
<script type='text/javascript' src='http://sisyphus-js.herokuapp.com/assets/application-09059f9f54cc3c3bff98487cf866644b.js'></script>
</head>
<body>
<form action="configurador.php" method="post" id="menuform" name="menuform">
<fieldset>
<legend id='itemPrompt'>Choose Item</legend>
<label>
<input type='checkbox' name='item' value="Value#01" />
<span>Value#01</span>
</label>
(...more...)
<input type="submit" name="submit" value="Send" />
</fieldset>
</form>
</body>
So there I have all my 'checkboxes' with values and names. I made some JavaScript functions but most important one is this one where I retrieve all values and send theme in an email:
function sendMail() {
var mailbody = "My Configurator: \n\n"
+ $('input[name="item"]')
.map(function(id, box){ return (box.checked ? "[x]" : "[_]") + " " + box.value;})
.get()
.join("\n");
var link = "mailto:mail#mail.com"
+ "?cc="
+ "&subject=" + escape("Configurator - Subject")
+ "&body=" + escape(mailbody);
window.location.href = link;
}
$(function(){
$( "#menuform" ).sisyphus();
});
And it's OK with just this. But I'm getting all checkboxes, even not checked ones, in that email. And could be perfect if I don't have to open a client mail, just send that mail from my server automatically.
Any solution for this variation?

Related

I am not able to call my php code from form submit, why is this?

I can't get the php code to run! Would anybody know what the problem is? I'm not sure of the way I called the pHp code makes sense. Everything works but a file is not saved.
The code is supposed to display a list of subjects in a bullet
pointed list as I ask the user to keep putting in subjects until
submitted.
The code is then supposed to save this list in a csv file like this
(Math, Biology, English etc) but I dont think the php code is
running.
<html>
<h1> Fill in Subjects </h1>
<input type='text' id='input' />
<input type='button' value='add subject' id = "add" />
<input type='text' id='input2' />
<input type='button' value='remove subject' id='remove' />
<div id='list'>
</div>
<p> When Submit button is clicked, you can not come back to this page!</p>
<form method="POST" action=''>
<input type='button' value='Submit' id = "subjectsub" name = "complete" />
</form>
<script type="text/javascript">
var subjectli = [];
document.getElementById("subjectsub").onclick = function(){
JSON.stringify(subjectli);
}
document.getElementById("remove").onclick = function(){
document.getElementById("list").innerHTML = "";
var toRemove = document.getElementById("input2").value;
var index = subjectli.indexOf(toRemove);
if (index > -1) {
subjectli.splice(index, 1);
}
var sList = "";
for (var I = 0; I < subjectli.length; I++)
{
sList = "<li>" + subjectli[I] + "</li>";
document.getElementById("list").innerHTML += sList;
}
document.getElementById("input2").value = ""; // clear the value
}
document.getElementById("add").onclick = function() {
var text = document.getElementById("input").value;
subjectli.push(text);
var li = document.createElement("li");
li.textContent = text;
document.getElementById("list").appendChild(li);
document.getElementById("input").value = ""; // clear the value
}
</script>
<?php
if (isset($_POST['complete']))
{
$subjectA=json_decode($_POST['jsondata']);
$fp = fopen('file1.csv', 'w');
foreach ($subjectA as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
}
?>
</html>
The input elements need to be within the form if you want them to be posted with the form submit.
<div id='list'>
</div>
<p> When Submit button is clicked, you can not come back to this page!</p>
<form method="POST" action=''>
<input type='text' id='input' />
<input type='button' value='add subject' id = "add" />
<input type='text' id='input2' />
<input type='button' value='remove subject' id='remove' />
<input type='button' value='Submit' id = "subjectsub" name = "complete" />
</form>
Form elements should be inside the form tags as the other answerer mentioned. And be sure to put the form processing file inside the form action attribute like this:
<form method="POST" action='myFileName.php'>

Keeping value of search box Javascript/HTML

I made a tool which make my work a little easier by inserting a value into a url in a new window on multiple sites. It was working quite well but now I am having the problem of the search value being cleared onsubmit.
Javascript:
<script language="JAVASCRIPT">
function run() {
var request = document.text.query.value;
var req = "";
var endofurl = "endofurl.html";
for(var i = 0; i < request.length; i++) {
var ch;
if((ch = request.substring(i, i + 1)) == " ") req += " ";
else req += ch;
}
if(document.search.website.checked) {
var website = open( "https://www.website.com/" + req, "website");
}
//--></script>
HTML:
<form name="search">
Please select the networks you want to use.
<p>
</center>
</p>
<div class="row">
<div class="column">
<br>
<input name="website" type="checkbox">Website to Search
<form name="text" onsubmit="run(); return false;">
<center>And enter your Query.</center>
<center>
<input name="query" placeholder="Steropodon" value="" size="50" type="TEXT">
<input value="Search" onclick="run()" type="BUTTON">
</center>
So far, return false had been working to keep the value of the input in the form="text" input name="query" but now it seems to clear it and reload the page. I'm not sure what changed.
You have errors in your code opening and closing the tags.
Try this code. It works:
<html>
<head></head>
<body>
Please select the networks you want to use
<div class="row">
<div class="column">
<br>
<input name="website" type="checkbox">Website to Search
<form name="text" onsubmit="run(); return false;">
<center>And enter your Query.</center>
<center>
<input name="query" placeholder="Steropodon" value="" size="50" type="TEXT">
<input value="Search" onclick="run()" type="BUTTON">
</center>
</form>
</div>
</div>
<script language="JAVASCRIPT">
function run() {
var request = document.text.query.value;
var req = "";
var endofurl = "endofurl.html";
for(var i = 0; i < request.length; i++) {
var ch;
if((ch = request.substring(i, i + 1)) == " ") req += " ";
else req += ch;
}
var checkbox = document.getElementsByName("website");
if(checkbox[0].checked) {
var website = open("https://www.website.com/" + req,
"website");
}
}
</script>
</body>
</html>
Hope it helps.
I fixed it. It was not the tags. I had only pasted a small amount of the total code to make it easier to read but I failed at making it easier to read. The problem was undefined inputs. I have been adding many if statements but didn't have a corrosponding checkbox. Oops.
Thanks for the help.

Add radio button input to textbox input and store it in a list?

I have a textbox where users can enter their name and 2 radio buttons, one for Mr. and one for Mrs. .
When the user hits the submit button I want a function to run that checks which radio button the user checked and add it to their name, then store it in a list.
For example lets say they enter their name as John and click the Mr. box. I want it to add Mr. to john and then store it in a list. So it would store Mr.John is a list.
Im at a loss as to how to do this, Heres what I've got so far:
var UserNames = []
var NameAdd = function() {
var name = document.getElementById("nametextbox").value;
UserNames.push("name");
}
If that code is correct it should take the input from the textbox and store it in a list.
Heres the css for the radio buttons:
#CheckBox1,#CheckBox2 {
float:left;
margin: 600px 20px 20px 60px;
color: #b2aba4;
}
And heres the html:
<div id="CheckBox1"><input type="radio" Name="Mr."/>Mr.</div>
<div id="CheckBox2"><input type="radio" Name="Mrs."/>Mrs.</div>
Any help is appreciated im at a loss here. Ik that it should be a if/else statement but past that im clueless.
I would change your markup to this:
<div id="CheckBox1"><input type="radio" name="salutation" value="Mr." />Mr.</div>
<div id="CheckBox2"><input type="radio" name="salutation" value="Mrs." />Mrs.</div>
and you can then get the value with this JavaScript:
var salutation = document.querySelector('input[name = "salutation"]:checked').value;
If you want it at Client side this may help you:
WORKING:DEMO
JS
$("button").click(function()
{
var curSex = $("input[type=radio]").val();
var curName = $("input[type=text]").val();
document.getElementById("print").innerHTML = "Hello" + " " + curSex + curName;
});
HTML
<div id="CheckBox1"><input type="radio" Name="Mr." value="Mr." />Mr.</div>
<div id="CheckBox2"><input type="radio" Name="Mrs." value="Mrs." />Mrs.</div>
Enter Name : <input type="text" name="name" />
<button>Submit</button>
<p id="print"></p>
<form name="send" method="POST">
<input type="text" name="name" id ="userName" />
<div id="CheckBox1"><input type="radio" id ="mr" value="Mr." Name="title"/>Mr.</div>
<div id="CheckBox2"><input type="radio" id ="mrs" value="Mrs." Name="title"/>Mrs.</div>
<input type="button" name="button" value="Submit" onClick="getInfo(this.form);" />
</form>
<p id="info"></p>
java script code
function getInfo(form) {
var userName = document.getElementById("userName");
var mr = document.getElementById('mr');
var mrs = document.getElementById('mrs');
var data = [];
if (userName.value !== "") {
if (mr.checked) {
data.title = mr.value;
mrs.checked = false;
} else if (mrs.checked) {
data.title = mrs.value;
mr.checked = false;
}
data.name = userName.value;
document.getElementById("info").innerHTML = "Hello:" + data.title + " " + data.name;
}
//console.log(data);
}
demo

Checkbox checked using javascript on tcpdf

I have a question about javascript that I using in TCPDF to generate PDF.
I use mix of php native and codeigniter with MySQL database to develop my App.
My Soryboard :
I have a field in my table like this that represntated like this :
$dataKind = $d['kindOf_request'];
// This code will be return a string like this : **Login, Printer, Monitor, Computer, Network, Other**
So, I use Javascript to split this string to convert into an array.
You know, TCPDF can write html. How to manipulated a checkbox that will be checked if matching with Element of this array. This is the code :
$dataKind = $d['kindOf_request'];
$html = <<<EOD
<body>
<form action="">
<input type="checkbox" name="request[]" id="Login" value="Login" > Login
<input type="checkbox" name="request[]" id="Printer" value="Printer" > Printer
<input type="checkbox" name="request[]" id="Monitor" value="Monitor" > Monitor
<input type="checkbox" name="request[]" id="Computer" value="Computer" > Computer
<input type="checkbox" name="request[]" id="Network" value="Network" > Network
<input type="checkbox" name="request[]" id="Lain-lain" value="Lain-lain"> Other
</form>
</body>
EOD;
$pdf->writeHTMLCell(0, 10, '', '', $html, $border = 0, $ln = 1, $fill = false, $reseth = true, $align = 'L', $autopadding = false);
$js = <<<EOD
var str = "$dataJenis";
var res = str.split(" ");
for (var i=0, item; item=res[i]; i++) {
item = item.replace(/,/g, "");
/*if item == id checkbox, then :
checkbox will be checked
*/
if (item == document.getElement ...) {
// Confused
# code...
}
//app.alert(item);
}
EOD;
$pdf->IncludeJS($js);
So million thanks for the help ...

On the Run Forms in HTML / Javascript

I have a query regarding form generation based on current inputs,
like in applications the text input appear based on our choice.
I am trying to make it work using JavaScript , but my code doesn't do anything:
<html>
<head>
<script>
function addInput() {
if (fields != 10) {
document.getElementById('d_div').innerHTML += "<input type='text' value='' /><br />";
fields += 1;
} else {
document.getElementById('d_div').innerHTML += "<br />Only 10 upload fields allowed.";
document.form.add.disabled=true;
}}
</script>
</head>
<body>
<div align = "center">
<form method = "post" action = "<?php echo $_SERVER['PHP_SELF']; ?>">
Select a Template<br />
<select name = "template" id = "rawquery">
<option>Select</option>
<option value = "Alpha query">Alpha</option>
<option value = "Betaquery">Beta</option>
<option value = "Gamma query">Gamma</option>
<option value = "Epsilon query">Epsilon</option>
</select>
<br/>
<input type = "submit" name = "submit"><br /><br />
</form>
</div>
<textarea name = "raw" rows = "10" cols = "50" id = "Raw">raw template</textarea>
<br /><br />
<form id="d_form">
<input type="submit" onclick="addInput()" name="newform" value="Click to enter values">
</form>
<div id="d_div"> </div>
</div>
<br> <br> <br> <br>
</body>
</html>
The code making drop-down menu is not used here.
When I click on the button to enter values it doesn't give me a new text area; can you please help, I am very new to this and learning?
where is 'fields'-initialization?
don't forget returning false, if really don't need to submit form #d_form clicking button #newform
You have a lot of problems with your tags. First make those right. I am giving an example
of creating dynamic tags. I think you can use it.copy and see how it works
<script type="text/javascript">
fields=0;
function addInput() {
textvalue=document.getElementById("raw").value;
var opt = document.createElement("option");
if (fields != 10) {
opt.text=textvalue;
document.getElementById('rawquery').options.add(opt);
fields += 1;
} else {
document.getElementById('d_div').innerHTML += "<br />Only 10 upload fields allowed.";
document.form.add.disabled = true;
}
}
</script>

Categories

Resources