I would like to send the selected objects to a email address.
here is a demo:
http://jsfiddle.net/62g3s8sz/
I know a email can be send with PHP and i have tried many ways but all unsuccessful.
The email needs to correspond with the items selected.
So if Cooler Master K-380 is selected with AMD FM2 A6-6400K Dual Core 3,9GHz i need it to list these items
Case : Cooler Master K-380 : price
Processor: AMD FM2 A6-6400K Dual Core 3,9GHz : price
And then send it to the email address that the person is logged in with.
i know that $loggedInUser->email will display the email address.
If anyone knows how to send all this information within a email to the logged in person that would be great.
HTML:
<script type="text/javascript" src="js/formcalc.js"></script>
<form method="POST" name="contactform" action="contact-form.php" id="computerform">
<div>
<div class="cont_order">
<fieldset>
<legend></legend>
<label>Case</label>
<br>
<label class='radiolabel'>
<input checked="checked" type="radio" name="selectedcase" value="2001" onclick="calculateTotal()" />Cooler Master K-350 - ($10)</label>
<br/>
<label class='radiolabel'>
<input type="radio" name="selectedcase" value="2002" onclick="calculateTotal()" />Cooler Master K-380 - ($20)</label>
<br/>
<br/>
<label>Processor</label>
<br>
<label class='radiolabel'>
<input checked="checked" type="radio" name="selectedprocessor" value="3001" onclick="calculateTotal()" />AMD FM2 A4-5300 Dual Core 3,4GHz - ($10)</label>
<br/>
<label class='radiolabel'>
<input type="radio" name="selectedprocessor" value="3002" onclick="calculateTotal()" />AMD FM2 A6-6400K Dual Core 3,9GHz - ($20)</label>
<br/>
<br/>
<label>Totale price</label>
<div class="total">
<div id="case"></div>
<div id="totalPrice"></div>
</div>
<br>
</fieldset>
</div>
<input type='submit' id='submit' value='Bestel' onclick="calculateTotal()" />
</div>
</form>
JavaScript code
var case_prices = new Array();
case_prices["2001"]=10;
case_prices["2002"]=20;
var processor_prices = new Array();
processor_prices["3001"]=10;
processor_prices["3002"]=20;
window.onload = function()
{
calculateTotal();
}
// getCasePrice() finds the price based on the selected case
// Here, we need to take user's the selection from radio button selection
function getCasePrice()
{
var casePrice=0;
//Get a reference to the form id="computerform"
var theForm = document.forms["computerform"];
//Get a reference to the case the user Chooses name=selectedcase":
var selectedCase = theForm.elements["selectedcase"];
//We loop through each radio buttons
for(var i = 0; i < selectedCase.length; i++)
{
//if the radio button is checked
if(selectedCase[i].checked)
{
//we set cakeSizePrice to the value of the selected radio button
//i.e. if the user choose the 8" cake we set it to 25
//by using the cake_prices array
//We get the selected Items value
//For example cake_prices["Round8".value]"
casePrice = case_prices[selectedCase[i].value];
//If we get a match then we break out of this loop
//No reason to continue if we get a match
break;
}
}
//We return the cakeSizePrice
return casePrice;
}
// getCasePrice() finds the price based on the selected case
// Here, we need to take user's the selection from radio button selection
function getProcessorPrice()
{
var processorPrice=0;
//Get a reference to the form id="computerform"
var theForm = document.forms["computerform"];
//Get a reference to the cake the user Chooses name=selectedprocessor":
var selectedProcessor = theForm.elements["selectedprocessor"];
//We loop through each radio buttons
for(var i = 0; i < selectedProcessor.length; i++)
{
//if the radio button is checked
if(selectedProcessor[i].checked)
{
//we set cakeSizePrice to the value of the selected radio button
//i.e. if the user choose the 8" cake we set it to 25
//by using the cake_prices array
//We get the selected Items value
//For example cake_prices["Round8".value]"
processorPrice = processor_prices[selectedProcessor[i].value];
//If we get a match then we break out of this loop
//No reason to continue if we get a match
break;
}
}
//We return the cakeSizePrice
return processorPrice;
}
function calculateTotal()
{
//Here we get the total price by calling our function
//Each function returns a number so by calling them we add the values they return together
var computerPrice = getCasePrice() + getProcessorPrice() + getCoolerPrice() + getMotherboardPrice();
//display the result
var divobj = document.getElementById('totalPrice');
divobj.style.display='block';
divobj.innerHTML = "Totale prijs: €"+computerPrice ;
}
Thanks :)
I don't like just pasting a link to the answer but ...
http://php.net/manual/en/function.mail.php
So all you need is something like this
$content = "..write it here yadda yadda whatever is your mail content ..";
$ok = mail($mailTo,"Hello, this is the mail subject",$content);
Note this will send plain mail, there are a few extra steps to make HTML mail, all covered on the link above. Good luck
Few reminders: it will probably not work on your local machine unless you have a mail daemon installed and working with PHP, and also you might need to tweak the last parameters on that mail() function depending on how PHP is installed.
In php, you send mails through the mail() function (or you could use an external mailer plugin), which requires a few basic concepts. Example:
$to = "email-from-user#some-email-client.com";
$subject = "You just made an order";
$body = $message;
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= "From: noreply#somewebsite.com";
if (mail ($to, $subject, $body, $headers)) {
echo "1";
}
Quickly explained, you need a few parameters for the function to work. I just moved over some items from my own mail function, but i ll explain. You need a target (the $to variable) a subject (the $subject variable and the content, which i defined here as $body ... now i added headers too, which is additional, but for you, it might be important. The first two lines allows you to use HTML in the email, which you can use to markup your mail, such as using tables. Also you can specify where the email came from.
I use an echo there to check if it got through the mail function, if so, i use that parameter in an ajax call return to put up an appending div.
Remember, calling an external stylesheet isnt working in this so preferly, you have to do inline styling on your elements.
edit
I see you re trying to get the totals from your fieldset up in the email. Since you use a div to show the end content, sending a form will not allow you to transfer the variable from the total. (btw, if you submit this form, you actually go with 3002 and 2001 for example as variables, instead of the names in the email, thus you got to do some query work to push out the right names) Since I asume these prices are also in a database, you can calculate from there on the price as fixed and push it out in a query as well, which you then have to use in the $body variable.
Trying to point you in the right direction
The PHP code must be in contact-form.php, or you must change that name in the HTML.
Use the mail() function of PHP.
In PHP, the form data is available in the superglobal variable $_REQUEST.
Try print_r($_REQUEST); to see what is in there.
Related
I have this strange issue, which is hard for me to describe to be honest.
For testing purposes I have set up a SQL db containing id (autoincrement), first name, last name.
I have 2 entries there.
I call the db and list the entries in inputs like this:
while($row = $result->fetch_assoc()) {
$id = $row['id'];
$fname = $row['fname'];
$lname = $row['lname'];
echo "<div id='$id'>
<form method='post'>
<p>ID: <input type='text' name='id' id='id".$id."' value='$id' /></p>
<p>New first name: <input type='text' name='fname' id='fname".$id."' placeholder='$fname' /></p>
<p>New last name: <input type='text' name='lname' id='lname".$id."' placeholder='$lname' /></p>
<input type='submit' name='update' class='update' value='ID = $id' />
</form>
</div>";
}
Works perfectly fine and I get a page with both entries and a button to update them.
I am updating them with this function
$('.update').click(function(){
var row = $(this).parent().parent().attr('id'); // I've stored the SQL id in the parent div
// construct the input ids so i know where I am getting the data from
var idSource = '#id'+row;
var fnameSource = '#fname'+row;
var lnameSource = '#lname'+row;
// store the input values in variables
var id = $(idSource).val();
var fname = $(fnameSource).val();
var lname = $(lnameSource).val();
// use ajax to update sql table
$.ajax({
url : 'aiai.php',
method : 'post',
data : {id: id, fname: fname, lname: lname},
success: function(response){
console.log(response);
}
});
});
I am doing this so that every entry can be edited & updated on it's own.
An while this basically working I am getting a strange lag.
Example:
I load the page, update the first name, click the update button --> Works
Then I edit the same entry again, click the update button --> i am
getting the old value again
When I refresh the page I get the name update I just saved
Lag continues until I refresh the page
I load the page, update the first name, click the update button --> Works
Then I edit the same entry again, click the update button --> i am getting the old value again
When I refresh the page I get the name update I just saved.
Lag continues until I refresh the page.
It's like that info gets cached in the browser.
BUT, and this confuses me:
When I hardcode the inputs where I am calling the values from, everything works perfect.
So when I use
var id = $('#id2').val();
... instead of
var id = $(idSource).val();
... I am not experiencing this lag.
Anyone got an idea what I am doing wrong?
i need a help here. i want to automatically update my iD whenever i submit my data. let me explain a bit more.
Here is the scenario when i submit a form the id of my page needs to update automatically. for example if i enter id 3 and submit the html form, when i open the form again it must check the Id from database and show the next id.
This means if the last data i entered has id 3 it then show me id 4 automatically when i refresh the page and want to submit new data
how can i add ID validation query in that code
need your expert advises.. thanks alot!!!
Html
<form action="survey-data-entry.php" name="1st-form" id="form-control" method="post" >
<label>Id.</label>
<input type="text" class="form-control" placeholder=" 0451211315" name="ID" id="id" required>
php
if(isset($_POST['ID'])){
$ID = $_POST['ID'];
$sql= "INSERT INTO phpstartup (ID, )
VALUES('$ID') ";
if(!mysql_query($sql))
{
die('caution' . mysql_error());
}
echo"1 record added";
}
You need to get the maximum of id + 1 from the query to use it for your next submission.
$rslt = mysql_query('SELECT MAX(ID) + 1 as nextId FROM phpstartup');
$row = mysql_fetch_assoc($rslt);
$nextId = $row['nextId'];
Now you can use the variable $nextId in your forms for re submission.
I have a table named, student_db which is like this :-
Name Gender Grade City
John Male 2 North
Dave Male 4 North
Garry Male 3 North
Chirsty Female 5 East
Monica Female 4 East
Andrew Male 3 East
Patrick Male 7 South
Maria Female 3 South
I need to select 3 students with this list, names of the students are taken as input. But there are some constraints :
1) 1 Female has to be selected.
2) A maximum of 2 persons from the same city can be selected.
3) Sum of the grade of the selected 3 persons cannot exceed 11.
4) Once three valid selections are made, rest of the checkboxes should freeze automatically.
5) If while selecting a person any of the constraint gets violated, that particular selections gets unchecked and a alert message is displayed to the user.
Is it possible to add so many constraints to a check box ??
EDIT
I have managed to add 2 constraints :-
1) If the grade sum exceeds 11, an alert message will get displayed.
2) Once three valid selections are made, rest checkboxes will get freezed.
This is what I've tried :-
<script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(function() {
var max = 3;
var checkboxes = $('input[type="checkbox"]');
checkboxes.change(function() {
var current = checkboxes.filter(':checked').length;
checkboxes.filter(':not(:checked)').prop('disabled', current >= max);
});
});
</script>
<script>
function jsFunction(element) {
var sum = 0,i;
var elements = document.getElementsByClassName('chkbox');
for (i = 0; i<elements.length; i++) {
if (elements[i].checked) {
sum += parseInt(elements[i].value);
}
}
if (sum > 11) {
alert("11 maximum grade allowed !!");
element.checked = false;
}
}
</script>
<form name='checkbox1[]' method="post" action="select_student.php">
<label class="cb1" for="checkbox1"> </label>
<input type="hidden" name="checkbox1[]" id="check" value="null">
<?php
session_start();
mysql_connect("localhost", "my_db", "my_password") or die (mysql_error ());
mysql_select_db("my_db") or die(mysql_error());
$strSQL = "SELECT Name,Grade FROM student_db";
$rs = mysql_query($strSQL);
echo "<b><h2>List of Students :-</h2></b>";
while($row = mysql_fetch_array($rs)) {
$man = $row['Name'];
echo '<input type="checkbox" value="'.$row['Name'].'|'.$row['Grade'].'" class="chkbox" name="checkbox1[]" onchange="jsFunction(this)" />';
echo $man;
}
?>
<br>
<input type="submit" value="SUBMIT" id="button1" style= "height:40px; width:150px; font-weight: bold; font-size:10;">
</form>
The JS function is used to check whether the Grade sum is exceeding 11 or not and the jQuery Functions freezes other boxes once 3 valid selections are made. But I am unable to add other constraints.
Sorry for the delayed response! I got caught up in some other stuff yesterday and had to pick back up this morning . . . hopefully, this will help you out.
What you have is a pretty good start . . . here's a few changes that I would suggest:
1) First off, some HTML changes:
store off all of your student data (i.e., the "gender", "grade", and "city" values) as data attributes in the checkbox, like this:
<input type="checkbox" value="NAME_VALUE" class="chkbox" name="checkbox1[]"
data-gender="GENDER_VALUE" data-grade="GRADE_VALUE" data-city="CITY_VALUE"
onchange="jsFunction(this)" />
next, since you are already using jQuery, for clarity and easy of maintenance in the future, apply the onchange event listener dynamically, rather than hardcoding it into the input, like this:
<input type="checkbox" value="NAME_VALUE" class="chkbox" name="checkbox1[]"
data-gender="GENDER_VALUE" data-grade="GRADE_VALUE" data-city="CITY_VALUE" />
. . . and, in the script, after the page load:
$(".chkbox").on("change", jsFunction);
And, finally (just as a heads up), if you intend to us a <label> tag with a for attribute (e.g., you are showing one for your "hidden" input), you will need a matching id attribute in yout <input>, in order for them to be paired.
2) As for your scripting, I threw together the following that accomplishes all of the validation checks that you were looking for and standardizes some of your coding (you had a heavily mixed use of jQuery and vanilla JS).
var MAX_CHECKED = 3;
var MAX_GRADE = 11;
$("document").ready(function() {
$(".chkbox").on("change", jsFunction);
});
function jsFunction() {
var sum = 0;
var cities = [];
var elements = $(".chkbox");
var checkedElements = elements.filter(":checked");
checkedElements.each(function() {
sum += parseInt($(this).data("grade"), 10);
cities.push($(this).data("city"));
});
var uniqueCities = cities.filter(function(currentCity, cityIndex, cityArray) {
return (cityIndex === cityArray.indexOf(currentCity));
});
if (sum > MAX_GRADE ) {
alert(MAX_GRADE + " maximum grade allowed!!");
$(this).prop("checked", false);
}
else if (uniqueCities.length !== cities.length) {
alert("You may not select more than one student from each city!!");
$(this).prop("checked", false);
}
else {
if (checkedElements.length >= MAX_CHECKED) {
if (checkedElements.filter("[data-gender='Female']").length < 1) {
alert("At least one female student must be selected!!");
$(this).prop("checked", false);
}
else {
elements.filter(':not(:checked)').prop('disabled', true);
}
}
else {
elements.filter(':not(:checked)').prop('disabled', false);
}
}
}
Most of the code should be pretty straightforward . . . let me touch on a couple of the key or more complex parts . . .
Globals - I set your global variables (MAX_CHECKED and MAX_GRADE) up at the top and outside of any functions, so that they are accessible anywhere and easy to update (i.e., you don't have to search through the code to find them).
"Setup code" - I moved your setup code from the jQuery(function() { that you used to $("document").ready(function() { simply for readablity. :) They do the same thing.
Event binding the checkboxes - as I mentioned, I did this dynamically rather than inline, using $(".chkbox").on("change", jsFunction);. Additionally, you'll notice that I changed the selector. Since each checkbox is tagged with the "chkbox" class, I selected based on that, it is significantly faster than $('input[type="checkbox"]')
The validation logic - basically, you want to catch invalid entries as soon as possible and you have rules that fall into two categories: rules that can be checked before the maximum number of selections have been met and rules that require the maximum. The "max grade" and "unique cities" checks should be caught as soon as they are hit, but you must wait until you've hit the maximum selections before you can check for gender, since the user can always check a female student later on, if they have not yet hit the max.
uniqueCities - the function used to create this value isn't quite as straighforward as the rest of the code, so I'll clarify it a little. It is using the .filter method that is native to Arrays, to trim down the selections to only unique values. It does this by doing a callback which checks to see if the index of the current item (i.e., cityIndex) is the same as the index of the first instance of that value (i.e., currentCity) in the array (i.e., cityArray). If it is, then that value is added to the "filtered" array (i.e., uniqueCities).
"undisabling" - I added in an else statement that re-enables the checkboxes if the maximum number of selections have been made, but then one of them is unchecked. This will allow the user to change their mind, even if they had already hit the max, at some point.
A couple of extra notes
1) You need to change the value of Patrick's to "6" at the most, in order to check that the "at least one female" logic is working . . . currently, the lowest combination of all male students, from unique cities, is John, Garry, and Patrick, but their grade total is 12, so it triggers the "grade sum is too high" validation first. :)
2) While I didn't cover the code for this, you need to develop a version of this validation logic for your "Submit" button as well. If you don't, then someone could select two boys and hit "Submit" and the "at least one female" logic would never be triggered.
One way would be to put the "at least one female" validation in its own method and calling both from the "I just clicked on a checkbox" validation and in a "I just clicked on the submit button" validation. The main difference would be that, for the submit, you would not check to see if the max number of selections had been made, before triggering the "female" check. That would also be a good place to add an "at least one selection has been made" validation, as well.
I have created a simple (but long) HTML form, i need the used to be able to save the form progress and return to it at a later date (security is not a big issue). But i am having trouble going about saving the form state and then recalling it later. (warning, im a noob)
So what is have is:
I have a form
<form action="phpSaveTry1.php" form method="post">
When the form is submitted with the save button
<INPUT TYPE = "Submit" Name = "Save" VALUE = "Save and Submit">
I try to save all the posted variables in a file on the server in the following way... (other suggestions are welcome)
$varNameArray = array("fname","mname","lname","comment","email","website","saveFile");
if (isset($_POST['Save'])) {
for($i = 0; $i < count($varNameArray); ++$i) { //go through every variable and add it to array
$arrayOfVars[$varNameArray[$i]] = ($_POST[$varNameArray[$i]]);
}
}
$saveFileName = "NameOfSavedState";
$var_str = var_export($arrayOfVars, true);
$var = "<?php\n\n\$$arrayOfVars = $var_str;\n\n";
file_put_contents(sprintf("/home/pansyc5/public_html/Jul17/SavedForms/%s.php",$saveFileName), $var);
Then in the html header where the form is contained i want to recall the variables
$saveFileName = "NameOfSavedState";
include sprintf("/home/pansyc5/public_html/Jul17/SavedForms/%s.php",$saveFileName);
and recall the values into the fields by first repopulating the variables
for($i = 0; $i < count($varNameArray); ++$i) { //go through every variable and declare it
$varNameArray[$i] = ( $arrayOfVars[$varNameArray[$i]] );
}
And then repopulating the form by setting the html values as e.g;
Last Name: <input type="text" name="lname" value="<?PHP print $lname; ?>">
I am new to website design, but this seems like a quite convoluted way of going about saving a form session ( not to mention, it is not working ).
What is the correct way of repopulating or saving a form state ?
Throw all of this code away. By writing data to a PHP file, you're creating a security nightmare. There's really no reason for most of your code. Try something simpler:
session_start();
$_SESSION['lastFormData'] = $_POST;
Then when you populate your form later...
echo '<input name="lname" value="' . htmlspecialchars($_SESSION['lastFormData']['lname']) . '" />';
I was wondering how someone would send and receive input data to and from a MySQL database when the form that is being submitted can have additional fields added to it (So one order form might have 10 input fields and another might have 30). Here is a snippet to give you an idea of what I am talking about - http://jsfiddle.net/gv0029/M84r7/
I saw an post about using arrays but it was from 4 years ago and am wanting to make sure whatever I do is still using best practices. Any and all help or ideas would be greatly appreciated! Thank you!
HTML:
<fieldset id="fence">
<div name="inputFence" class="inputFence">
<legend><strong>Fence Description</strong>
</legend>
<label>Footage:
<input name="footage_1" class="footage" />
</label>
<label>Fence Height</label>
<select name="fenceHeight_1" class="fenceHeight">
<option value="select">Select Fence Height</option>
<option value="6" id="fH6">6 Ft.</option>
<option value="8" id="fH8">8 Ft.</option>
</select>
<legend><strong>Post Type</strong>
</legend>
<label>Post Quantity:
<input name="postQuantity_1" class="postQuantity" />
</label>
<label>Picket Quantity
<input name="picketQuantity_1" class="picketQuantity" />
</label>
</fieldset>
<div>
<input type="button" id="btnAddFence" value="Add Another Fence" />
<input type="button" id="btnDelFence" value="Remove Fence" />
</div>
</form>
JS
//Dynamic Fence Input Fields
$('#btnAddFence').click(function () {
// create the new element via clone()
var newElem = $('.inputFence:last').clone();
// insert the new element after the last "duplicable" input field
$('.inputFence:last').after(newElem);
// enable the "remove" button
$('#btnDelFence').removeAttr('disabled');
//get the input name and split into array (assuming your clone is always last)
var parts = $('.fenceHeight:last').attr('name').split("_");
//change the second element of the array to be one higher
parts[1]++;
//join back into a string and apply to the new element
$('.fenceHeight:last').attr('name', parts.join("_"));
//do the same for other two inputs
parts = $('.postQuantity:last').attr('name').split("_");
parts[1]++;
$('.postQuantity:last').attr('name', parts.join("_"));
parts = $('.footage:last').attr('name').split("_");
parts[1]++;
$('.footage:last').attr('name', parts.join("_"));
parts = $('.6foc:last').attr('name').split("_");
parts[1]++;
$('.6foc:last').attr('name', parts.join("_"));
parts = $('.railQuantity:last').attr('name').split("_");
parts[1]++;
$('.railQuantity:last').attr('name', parts.join("_"));
});
$('#btnDelFence').click(function () {
//remove the last inputFence
$('.inputFence:last').remove();
// if only one element remains, disable the "remove" button
if ($('.inputFence').length == 1) $('#btnDelFence').attr('disabled', 'disabled');
});
$('#btnDelFence').attr('disabled', 'disabled');
So it sounds like you have an unknown number of fields and you are looking for an easy way to send them to MySql. So I'm assuming you are calling a stored procedure but don't know how to deal with the unknown parameters. I would take the form and either serialize it into JSON or turn all the $_POST values into a XML object. Then you would only need to pass that single object into your MySql stored procedure. Once inside you could use some loops and XML function to do what you have to do. This way it wouldn't matter if your submitting 10 fields or 100 fields, the call to the stored proc would always be the same. I do this with a site and it works pretty good. Not on that PC to where I can get the code right now though. These might help....
To turn the PHP $_POST into XML: http://davidwalsh.name/watch-post-save-php-post-data-xml
Some MySql XML function to use once you're inside the stored proc: http://dev.mysql.com/doc/refman/5.1/en/xml-functions.html
I could help more later when I get on my other PC.. Hope this helps.
UPDATE: Here is how I grab all $_POST data and turn it into a valid XML document...
//Grab all the POST info, turn it into a valid XML object and store it
$postData = null;
if($_SERVER['REQUEST_METHOD'] == 'POST' && count($_POST) > 0) $postData = assocArrayToXML('POST_DATA',$_POST);
//The assocArrayToXML returns the XML object with page breaks, we need a stright non-breaking string
//so that the flexigrid can display the results properly.
$postData = str_replace(chr(13), '', $postData);
$postData = str_replace(chr(10), '', $postData);
And this is the assocArrayToXML function...
function assocArrayToXML($root_element_name,$ar)
{
$xml = new SimpleXMLElement("<?xml version=\"1.0\"?><{$root_element_name}></{$root_element_name}>");
$f = create_function('$f,$c,$a','
foreach($a as $k=>$v) {
if(is_array($v)) {
$ch=$c->addChild(htmlspecialchars($k));
$f($f,$ch,$v);
} else {
$c->addChild($k,htmlspecialchars($v));
}
}');
$f($f,$xml,$ar);
return $xml->asXML();
}
Serialize your form and send. In the server side unserialize it and insert to database
var str = $( "form" ).serialize();
Reference
http://api.jquery.com/serialize/