Sending an email with PHP/Javascript submit button - javascript

I will try and be brief. When a user selects items in a checkbox, I want them to be able to press a submit button and it will send an email of the ingredients to a static email address. I am trying to store the values of the check boxes in an array called finalOrder, and have that array in the contents of the email.
I am fairly new to both languages, can I use the submit button to call the PHP code? Is the PHP written correctly? I am not too sure how to go about this.
Here is what I have so far.
<div>
<input type="checkbox" name="foodType" data-name="Chicken Thighs"> <label
for="chickenThighs">Chicken Thighs</label>
<input type="checkbox" name="foodType" data-name="Chicken Breast"> <label
for="chickenBreast">Chicken Breast</label>
<input type="checkbox" name="foodType" data-name="Chicken Leg"> <label
for="chickenLeg">Chicken Leg</label>
</div>
<div id='results'>
</div>
<script type="text/javascript">
var finalOrder = [];
document.querySelectorAll('input[name=foodType]').forEach(elem => {
elem.addEventListener('change', updateList);
});
function buildList ()
{
let list = '<ul>';
finalOrder.forEach(str => {
list += "<li>" + str + '</li>';
});
list += '</ul>';
return list;
}
function updateList ()
{
finalOrder = []; // Reset this array so that we can populate it with the new checkbox answers.
document.querySelectorAll('input[name=foodType]').forEach(v => {
if (v.checked) {
finalOrder.push(v.dataset.name);
}
});
document.querySelector('#results').innerHTML = buildList();
}
</script>
<input type="submit" value="Submit">
<?php
// the message
$msg = finalOrder;
// use wordwrap() if lines are longer than 70 characters
$msg = wordwrap(finalOrder($msg,70));
// send email
mail("my#email.com","New Order",$msg);
?>

There is one thing, missing so far.
A form tags to help post the data for the server for processing by PHP language so the file has to be saved as a PHP file and HTML. In the snippet I saved it as thisFile.php.
You can also consider the approach stated by #jaaba
<div>
<form method="POST" action="thisFile.php">
<input type="checkbox" name="foodType" data-name="Chicken Thighs"> <label
for="chickenThighs">Chicken Thighs</label>
<input type="checkbox" name="foodType" data-name="Chicken Breast"> <label
for="chickenBreast">Chicken Breast</label>
<input type="checkbox" name="foodType" data-name="Chicken Leg"> <label
for="chickenLeg">Chicken Leg</label>
</div>
<input type="submit" value="Submit">
</form>
<div id='results'>
</div>
<script type="text/javascript">
var finalOrder = [];
document.querySelectorAll('input[name=foodType]').forEach(elem => {
elem.addEventListener('change', updateList);
});
function buildList ()
{
let list = '<ul>';
finalOrder.forEach(str => {
list += "<li>" + str + '</li>';
});
list += '</ul>';
return list;
}
function updateList ()
{
finalOrder = []; // Reset this array so that we can populate it with the new checkbox answers.
document.querySelectorAll('input[name=foodType]').forEach(v => {
if (v.checked) {
finalOrder.push(v.dataset.name);
}
});
document.querySelector('#results').innerHTML = buildList();
}
</script>
<?php
// the message
$msg = finalOrder;
// use wordwrap() if lines are longer than 70 characters
$msg = wordwrap(finalOrder($msg,70));
// send email
mail("my#email.com","New Order",$msg);
?>

Related

Passing checkbox array to GAS?

I am using Google App Script to create an HTML sidebar in Sheets. I want to have several checkboxes to select and pass the values back to GAS, preferably as an array. I have been looking up solutions and was using this as a guide. Here is my GAS code:
function showSidebar() {
var array = ["A","B","C","D","E"];
var html = HtmlService.createTemplateFromFile('page');
html.cols = array;
var html = html.evaluate().setTitle('Example');
SpreadsheetApp.getUi()
.showSidebar(html);
}
function displayToast(columns) {
SpreadsheetApp.getActive().toast("Output: " + columns);
}
The toast is there to test my setup, but it doesn't display when I click the submit button.
Here is the 'page' HTML:
<body>
<p>Which columns should be included in the email?</p>
<? for(var i = 0; i < cols.length; i++) { ?>
<input type="checkbox" name="col" id="<?= cols[i] ?>" value="<?= cols[i] ?>">Col
<?= cols[i] ?></input>
<? } ?><br>
<button id="btn">Submit</button> <br>
</body>
<script>
document.getElementById('btn').onclick = function() {
var markedCheckbox = document.getElementsByName('col');
google.script.run.displayToast(markedCheckbox);
}
</script>
The sidebar displays correctly, but I just can't get the checkbox values to pass over to the GAS side.
TIA.
You can't pass the HTML element to Apps Script. You have to send only the values:
document.getElementById('btn').onclick = function() {
var markedCheckbox = Array.from(document.getElementsByName('col'))
.filter(x => x.checked)
.map(x => x.value)
google.script.run.displayToast(markedCheckbox);
}

JavaScript Checkbox

I am having troubles with a script with JS, I am still learning but I am stuck for a while.
The solution should be,
IF a checkbox is checked and the value is "" <-- the msgbox should say an message that the textbox should be filled with a value, and so for each checked checkbox, if you uncheck the checkbox, it should dissapear.
Code of 2 checkboxes in html page
<label>
bangkirai
<input id="chk_bangkirai" type="checkbox" onchange="enableTextBox()" />
</label>
<input type="text" id="bangkirai" name="bangkirai" disabled onchange="enableTextBox()" />
<label>
beukenhout
<input id="chk_beukenhout" type="checkbox" />
</label>
<input type="text" id="beukenhout" name="beukenhout" disabled/>
and the JavaScript, I made for each checkbox an other function, but I need to combine the error message in the same msgbox.
function enableTextBox() {
divOutput = document.getElementById("msgbox2");
strValideer = "<ul>";
if (document.getElementById("chk_bangkirai").checked === true) {
document.getElementById("bangkirai").disabled = false;
}
else {
document.getElementById("bangkirai").disabled = true;
}
if (document.getElementById("bangkirai").value === "") {
strValideer += "<li><b>bangkirai: </b>verplicht veld</li>";
}
strValideer += "</ul>";
divOutput.innerHTML = strValideer;
}
function enableTextBox2() {
divOutput = document.getElementById("msgbox2");
strValideer = "<ul>";
if (document.getElementById("chk_beukenhout").checked === true) {
document.getElementById("beukenhout").disabled = false;
}
else {
document.getElementById("beukenhout").disabled = true;
}
if (document.getElementById("beukenhout").value === "") {
strValideer += "<li><b>beukenhout: </b>verplicht veld</li>";
}
strValideer += "</ul>";
divOutput.innerHTML = strValideer;
}
I should probably use an array or an for each itteration ... but I can only find examples with forms ...
I will keep looking for a solution myself, but I hope I can get some inspiration here by experienced coders.
Thanks in advance
You could simplify this a lot and make it more... Concise and less dependent on which checkbox you have. We will do this with an external script and no onClick attributes on our HTML. This will enable us to separate our logic code from our design code. I will also use a placeholder instead of value, as it will create issues when people need to start entering a value (aka, you need to only have the text there when theres no value etc...) It just makes it more complicated.
Since we are dealing with numbers ('stuks' or amounts), lets also only allow number values to be inserted. Lastly, I have not bothered to replicate your HTML as I think the simplified example will make it easier to understand. Update I have also added the required and disabled sattributes here, settings your input to required when the checkbox is checked and disabled when not.
Check the below snippet for comments on the steps taken to do this:
// First, let select all fieldsets like this:
var fieldsets = document.querySelectorAll( 'fieldset.checkbox-message' );
// Lets loop through them
for( let i = 0; i < fieldsets.length; i++ ){
// Lets create variables to store our fieldset, checkbox and input for later use.
let fieldset = fieldsets[ i ];
let checkbox = fieldset.querySelector( 'input[type="checkbox"]' );
let input = fieldset.querySelector( 'input[type="number"]' );
// Lets also store the message we put in placeholder
// We will also give it a default value,
// in case you forget to set the placeholder.
let message = input.placeholder || 'Please fill in the amount';
// Now lets define a function that will fill the placeholder
// based on the checked value of the checkbox
// We will be storing it in a variable because of the scope of a `for` block.
// If you would use function setState() it might be defined globally
// So multiply checkboxes would not work.
let setState = function(){
if( checkbox.checked ){
input.placeholder = message;
input.disabled = false;
input.required = true;
} else {
input.placeholder = '';
input.disabled = true;
input.required = false;
}
}
// Now lets listen for changes to the checkbox and call our setState
checkbox.addEventListener( 'change', setState );
// Lrts also call setState once to initialise the correct placeholder
// for our input element to get started. This will remove any placeholders
// if the checkboxes are unchecked.
setState();
}
<fieldset class="checkbox-message">
<label for="bangkirai">Bangkirai</label>
<input type="checkbox" id="bangkirai" />
<input type="number" placeholder="Tell us, how many 'bangkirai'?" />
<span>stuks</span>
</fieldset>
<fieldset class="checkbox-message">
<label for="beukenhout">Beukenhout</label>
<input type="checkbox" id="beukenhout" />
<input type="number" placeholder="How many 'beukenhout'?" />
<span>stuks</span>
</fieldset>
Good luck coding!
#somethinghere's answer is concise but if we modify your answer as it is you could check this
function enableTextBox() {
bangkirai_validation = document.getElementById("bangkirai_validation");
if (document.getElementById("chk_bangkirai").checked === true) {
document.getElementById("bangkirai").disabled = false;
}
else {
document.getElementById("bangkirai").disabled = true;
bangkirai_validation.style.display='none';
return;
}
if (document.getElementById("bangkirai").value =="") {
bangkirai_validation.style.display='block';
}else
{
bangkirai_validation.style.display='none';
}
}
function enableTextBox2() {
beukenhout_validation = document.getElementById("beukenhout_validation");
if (document.getElementById("chk_beukenhout").checked === true) {
document.getElementById("beukenhout").disabled = false;
}
else {
document.getElementById("beukenhout").disabled = true;
beukenhout_validation.style.display='none';
return;
}
if (document.getElementById("beukenhout").value == "") {
beukenhout_validation.style.display='block';
}else
{
beukenhout_validation.style.display='none';
}
}
<fieldset>
<legend>Bestel gegevens</legend>
<div class="container">
<div class="row">
<div class="span7 id=" houtsoorten"">
<div class="control-group">
<label class="control-label">
bangkirai
<input id="chk_bangkirai" type="checkbox"
onchange="enableTextBox()" >
</label>
<div class="controls">
<div class="input-append">
<input class="inpbox input-mini"
type="number" id="bangkirai" name="bangkirai" placeholder="aantal" disabled
onkeyup="enableTextBox()" onchange="enableTextBox()">
<span class="add-on">stuks</span>
<div style="display:none;" id="bangkirai_validation">Please enter a value</div>
</div>
</div>
</div>
<div class="control-group">
<label class="control-label">
beukenhout
<input id="chk_beukenhout" type="checkbox" onchange="enableTextBox2()" >
</label>
<div class="controls">
<div class="input-append">
<input class="inpbox input-mini"
type="number" id="beukenhout" name="beukenhout" placeholder="aantal"
disabled onkeyup="enableTextBox2()" onchange="enableTextBox2()" >
<span class="add-on">stuks</span>
<div style="display:none;" id="beukenhout_validation">Please enter a value</div>
</div>
</div>
</div>

Send only filled fields via GET

Look at simple form below:
<form method="GET" action="index.php">
<input type="text" name="price_min" >Min
<input type="text" name="price_max" >Max
</form>
When I send form with filled only one field, in my url I get empty values for not filled keys
(ex. index.php?price_min=).
Question:
How to remove empty keys from url?
You can parse serialized string and remove blank values. Then you can use post to necessary api using jQuery.
Sample
JSFiddle
$("#btn").on("click", function() {
var formjson = $("#frmTest").serialize();
var result = formjson.split("&").filter(function(val) {
return val.split("=")[1].length > 0;
}).join("&")
console.log("Serialized String:", formjson);
console.log("Processed String:", result);
// $.get('action.php', formjson, function(response){ ... })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form id="frmTest">
<input type="text" name="price_min">Min
<input type="text" name="price_max">Max
</form>
<button id="btn">Test Serialize</button>
Use jQuery to send the fields like this
$('your_form').submit(function() {
var min_price = $("#min_price").val();
var max_price = $("#max_price").val();
var string = "";
if(min_price.length > 0){
string += "min_price="+min_price
}
if(max_price.length > 0){
string += "&max_price="+max_price
}
window.location.href = 'index.php?'+string;
});
Hope it helps!

get value from HTML form with Javascript and then display them on html

This is my first post ever! So I am currently studying front end web development online. I have come across a problem! I am trying to get input from a user HTML form and display those values back on the HTML document. When I do it using javascript work but when using the form it dont.
see my code in codepen : http://codepen.io/kevin1616/pen/KdOvwy
My html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Contact List</title>
</head>
<body>
<header>
<h1> ContactBook.com </h1>
</header>
<section id="body">
<form method="post">
<input type="text" id="name" ><br>
<input type="text" id="last" ><br>
<input type="text" id="phone" ><br>
<input type="text" id="address" ><br>
<input type="submit" id="create_new_contact" >
</form>
<ol id="people">
</ol>
</section>
<script src="js.js"></script>
</body>
</html>
my javascript
// JavaScript Document
// CONTACTS CONTRUCTOR OBJECT
var contacts = function ( ) {
this.name = [];
this.lastName= [];
this.phoneNumber = [];
this.address= [];
};
contacts.prototype.add = function(name, last, number, address) {// Add method to add contacts
this.name.push(name);
this.lastName.push(last);
this.phoneNumber.push(number);
this.address.push(address);
}
contacts.prototype.toHTML = function (i) {// toHTML method formats how html will be displayed
var htmlString ="<li>";
htmlString +="<p>" + this.name[i] + "<p>";
htmlString +="<p>" + this.lastName[i] + "<p>";
htmlString +="<p>" + this.phoneNumber[i] + "<p>";
htmlString +="<p>" + this.address[i]+ "<p>";
htmlString +="</li>";
return htmlString;
};
contacts.prototype.renderElement = function (list) {// method for sending input to html
for ( var i=0; i < this.name.length; i++) {
list.innerHTML+= this.toHTML(i);
}
};
var addingContact = new contacts();// creating new instance of contructor
addingContact.add("Kevin", "Silvestre" ,"781 582 4449", "26 endicott st");// using the add method to add contacts to my list
var itemsTorender = document.getElementById("people");// select where in the html the elemtents will be rendered
addingContact.renderElement(itemsTorender);// render elements to html
You Just Need A function which call during submit form to get form data that time and show it in list
function saveData(){
var name = document.getElementById("name").value;
var last = document.getElementById("last").value;
var phone = document.getElementById("phone").value;
var address = document.getElementById("address").value;
addingContact.add(name,last ,phone, address);// using
var itemsTorender = document.getElementById("people");// select where in the html
addingContact.renderElement(itemsTorender);// render elements to html
return false; // this will stop default submit of form (because by default form submit on "action" url if no action is define than on same page )
}
and you need to call it like
<form method="post" action="#" onsubmit="return saveData()">
Fiddle

Use one jQuery function multiple times for several form inputs

I got a question in which I hope someone can help me
I have this script:
File test.php:
<script>
$(document).ready(function() {
var min_chars = 1;
var characters_error = 'Write at least '+ min_chars +' character';
var checking_html = 'Getting information...';
$('#get_information').click(function(){
if($('#idprice').val().length < min_chars){
$('#results_gotten').html(characters_error);
}else{
$('#results_gotten').html(checking_html);
check_availability();
}
});
});
function check_availability(){
var idprice = $('#idprice').val();
$.get("check_idprice.php?id="+$("#idprice").val(), function(data){
$("#results_gotten").html(data);
$("#results_gotten").show();
});
}
</script>
<input name="idprice" type="text" id="idprice" />
<input type="button" id="get_information" value="Checar"><br>
<div id="results_gotten"></div>
And a second file check_idprice.php
if (isset($_GET['id'])) { $id = $_GET['id']; } else { die ('No information'); }
$result = mysql_query("SELECT * FROM `sm_prices` WHERE `productid` = '". $id ."'");
$noresults = mysql_num_rows($result);
if($noresults > 0){
echo $noresults." found";
}else{
echo "No results found";
}
And it works perfectly, you can see it in action here:
http://www.enteratenorte.org/starmexico/test.php (You can search of 15-1 to get a result)
or here:
http://jsfiddle.net/EnterateNorte/hpT66/ (wont get you any result since it need a DB)
How ever, I would like to have multiple filds in the same test.php file, something like this:
<input name="idprice1" type="text" id="idprice1" />
<input type="button" id="get_information1" value="Check"><br>
<div id="results_gotten1"></div>
<input name="idprice2" type="text" id="idprice2" />
<input type="button" id="get_information2" value="Check"><br>
<div id="results_gotten2"></div>
<input name="idprice3" type="text" id="idprice3" />
<input type="button" id="get_information3" value="Check"><br>
<div id="results_gotten3"></div>
It could be 3 or more fields
How can this be achived using one single code?
You could wrap each block in a parent DIV:
<div class="retrieveInfo">
<input name="idprice1" type="text" id="idprice1" class="retrieveInfoText" />
<input type="button" id="get_information1" class="retrieveInfoSubmit" value="Check"><br>
<div id="results_gotten1" class="retrieveInfoResults"></div>
</div>
Then your JS might look something like this:
<script>
$(document).ready(function() {
var min_chars = 1
, characters_error = 'Write at least '+ min_chars +' character'
, checking_html = 'Getting information...'
, infoContainer = $('.retrieveInfo'); // this selects all the containers with this css class
/// now you can loop through each of the containers found...
infoContainer.each(function(){
var self = $(this) // $(this) refers to the current "container"
, infoSubmit = self.find('.retrieveInfoSubmit') // find button
, infoText = self.find('.retrieveInfoText') // find text box
, infoResults = self.find('.retrieveInfoResults'); // find result div
// since this is a loop, this click handler will be attached to all buttons found
infoSubmit.click(function(e){
// stop the browser from submitting the form (default action)
e.preventDefault();
// check if the info validates
if( infoText.val().length < min_chars){
infoResults.html(characters_error);
// returning here will stop execution of the function, no need for else
return false;
}
infoResults.html(checking_html);
// modified the funciton to accept some arguments
check_availability(infoText.val(), infoResults);
});
});
});
/**
* checkVal is the user input
* resultDiv is the jQuery object that points to the results for this container
*/
function check_availability(checkVal, resultDiv){
$.get("check_idprice.php?id=" + checkVal, function(data){
resultDiv.html(data).show();
});
}
</script>
Try something similar to the following
for(var i=0;i<3;i++) {
$('#get_information'+i).click(function(){
if($('#idprice'+i).val().length < min_chars){
$('#results_gotten'+i).html(characters_error);
}else{
$('#results_gotten'+i).html(checking_html);
check_availability(i);
}
});
}
function check_availability(i){
var idprice = $('#idprice'+i).val();
$.get("check_idprice.php?id="+$("#idprice"+i).val(), function(data){
$("#results_gotten"+i).html(data);
$("#results_gotten"+i).show();
});
}

Categories