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']) . '" />';
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 am designing an e-shop that allows profile registration. I need to have both Javascript & PHP validation for the registration form. (so when any of the fields are empty, I need to get a pop-up message that lets me know which specific field is empty + display on the screen beside the required field a visual message to advise the user where they need to correct the issue)
so far it is not working because my JS validation form activates onsubmit and my PHP is on action. I realize onsubmit activates before action and thus not allowing 'action' to go through.
I tried changing it from 'action' to 'onclick', but onsubmit also activates first and does not allow the PHP to work.
Here's my code for the form (I only included the first name portion so it won't get too long)
<form method="post" onclick="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" name="myForm" onsubmit="return validateForm()" style="border:1px solid #ccc">
<label><b>First Name</b></label>
<input type="text" name="firstName" placeholder="">
<?php echo $fnameErr;?>
<button type="submit" class="signupbtn" name="submit">Submit</button>
Here's my PHP code:
<?php
$fnameErr = "";
$fname = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["firstName"])) {
$fnameErr = "Name is required";
}
else {
$fname = test_input($_POST["firstName"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
I know the PHP code works, because if I delete the JS validation, it works as intended. I appreciate the help.
Please let me know if I need to add any extra information. Also, this hasn't been my first stop. I've been googling and trying to figure out how to fix this issue for hours to no avail...
This is the JS function being called (which also works as intended) this is also the shortened version to include only the name, the rest works the same, more if statements:
function validateForm() {
"use strict";
var fn = document.forms.myForm.firstName.value;
var ln = document.forms.myForm.lastName.value;
var em = document.forms.myForm.email.value;
var phone = document.forms.myForm.phone.value;
var pass = document.forms.myForm.psw.value;
var pass2 = document.forms.myForm.psw2.value;
if (fn === "") {
window.alert("First name must be filled out");
return false;
}
}
<input type="text" name="firstName" required>
You don't need any JavaScript.
Furthermore:
<form action="" method="post">
You don't need to specify the action if you're posting back to the current page. Using $_SERVER['PHP_SELF'] is potentially a vulnerability if you're not careful, and also breaks "pretty URLs" if you have them.
As said by #Niet The Dark Absol you can use the required but if you insist you can add e.preventdefault to prevent form from submitting in case of errors. We can elaborate properly if we can have a glimpse at your Javascript function.
You should change your onsubmit part and remove the onclick. Also your form is not valid as there is no action.
document.getElementById('myForm').addEventListener('submit',validateForm);
function validateForm(e) {
"use strict";
console.log(document.forms.myForm.firstName.value);
var fn = document.forms.myForm.firstName.value;
if (fn === "") {
window.alert("First name must be filled out");
e.preventDefault();
return false;
}
}
<form action="https://stackoverflow.com/" method="post" id="myForm">
<input type="text" name="firstName" >
<input type="submit">
</form>
There was a couple mistakes... But mainly what cause your problem is that onsubmit="return validateForm()". I also added e.preventDefault() it is to prevent the form submission if there is an error.
Im pretty new with javascript programming.
I have some .php code, where 2 dropdown lists (in the same FORM) are populated by 2 different mysqli queries, this works without any problem.
Im trying to get javascript to handle the selected parts of the dropdown lists, with onchange, this works for only one dropdown list, and i cant really figure out how to get around this one.
This is the code that works with one dropdown menu, and it updates automaticly the page without submitting:
$chosen_location = $_GET['Lid'];
$chosen_car = $_GET['Cid'];
?>
<script type="text/javascript">
function changeDropDown(dropdown){
var location = dropdown.options[dropdown.selectedIndex].value;
*var car = dropdown.options[dropdown.selectedIndex].value;*
document.getElementById("form1").action = "test.php?Lid=" + location + "&Cid=" + car;
document.getElementById("form1").submit();
}
</script>
Part of the .php code:
<select size="1" name="form_location_id" id="form_location_id" onchange='changeDropDown(this);'>
<option value = <?php echo ($location_id) ?> selected><?php echo ($location_name) ?></option>
<select size="1" name="form_car" id="form_car" onchange='changeDropDown(this);'>
<option value = <?php echo ($car_type_id) ?>><?php echo "" . ($car_class) . " - " . ($car_manufacturer) . " - " . ($car) . "" ?></option>
The italic marked I know will not catch the correct value, but this is where im at right now...
How is it possible to get an action URL with both selected values ? as this is going to be used in a mysqli query to show data from the actual selection
Thanks in advance... :)
Currently, you are submitting the form through JavaScript. If the selects are inside the form, their values will automatically be submitted when you submit the form. You don't even have to change the action of the form.
So, you can just generate a normal form (including submit button, if you will), and it will work. Then, add a little JavaScript sauce to make it submit automatically.
The code below does just that. JavaScripts adds a class to the body. This is a way to easily change styling based on JavaScript being enabled or not. In this case, I use it to hide the submit button, which is only needed in a non-JavaScript situation.
Then, I bind the on change handler, not unlike yours, to submit the form when a value is selected. By giving the selects a proper name, their values will automatically be added as intended.
Note how the event handlers are bound through code. You don't have to hardcode any calls to JavaScript in the HTML, so you can keep the HTML clean and separate (readability!).
// Bind to load event of the window. Alternatively, put the script at the end of the document.
window.addEventListener("load", function() {
// Indicate that JavaScript works. You can use this to style the document, for instance
// hide the submit button, if the form is automatically submitted on change..
document.body.classList.add("js");
// With JavaScript, you can automatically submit the form, but you still don't have to modify it.
var theform = document.getElementById("theform");
var selects = document.querySelectorAll("#theform select");
for (var i = 0; i < selects.length; ++i) {
selects[i].addEventListener("change",
function() {
alert("submitting now");
theform.submit();
});
}
});
.js button[type="submit"] {
display: none;
}
<!-- Just a form with selects is enough. You don't even have to have JavaScript to post this. -->
<form id="theform" action="test.php" method="get">
<select name="Lid">
<option>Example...</option>
<option>Use PHP,</option>
<option>to fill these.</option>
</select>
<select name="Cid">....</select>
<button type="submit">Post</button>
</form>
You can update your code to following
function changeDropDown(){
var elLocation = document.getElementById('form_location_id');
var elCar = document.getElementById('form_car');
var location = elLocation.options[elLocation.selectedIndex].value;
var car = elCar.options[elCar.selectedIndex].value;
document.getElementById("form1").action = "test.php?Lid=" + location + "&Cid=" + car;
document.getElementById("form1").submit();
}
try to do this
<script>
// get select elements
var form_location_id = document.getElementById('form_location_id');
var form_car = document.getElementById('form_car');
// on change
form_location_id.addEventListener('change', changeDropDown1);
form_car.addEventListener('change', changeDropDown2);
</script>
And change the 'changeDropDown1' and 'changeDropDown2' to your handler function
try this
<script type="text/JavaScript">
var dropdownLocation = document.getElementById("form_location_id");
var dropdownCar = document.getElementById("form_car");
function changeDropDown() {
var location = dropdownLocation.options[dropdownLocation.selectedIndex].value;
var car = dropdownCar.options[dropdownCar.selectedIndex].value;
document.getElementById("form1").action = "test.php?Lid=" + location + "&Cid=" + car;
document.getElementById("form1").submit();
}
</script>
dropdownLocation et dropdownCar are outside the function to save time because this 2 vars need only to be set one time
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.
This wordpress stuff driving me mad again.
I have an output page which uses a short code to call a function (Stores)... the code of which in part is beneath.
It has a dropdown and a table of data, ..the data being dependant on the selected option of the drop down.
I use javascript to set the hidden input...successfully.
In fact I tried a normal, non hidden input as well...same result,..on server side, with$_POST["txtSelection"] or
$_POST["hdnSelect"]
But when I try get it's value on the php server side code, it is empty,..
How on earth do I retrieve it?
the hidden input is inside the form tag.
<?php
function Stores()
{
global $wpdb;
global $MyPage;
$MyPage = str_replace( '%7E', '~', $_SERVER['REQUEST_URI']);
?>
<form name="frmSB_stores" method="post" action="<?php echo $MyPage ?>">
<input type="hidden" name="hdnSelect" id="hdnSelect" value="">
<input type="text" name="txtSelection" size="19" id="txtSelection" value="">
<script type="text/javascript">
function SetDDLValueOnChange (objDropDown) {
var objHidden = document.getElementById("hdnSelect");
if ( objDropDown.value.length > '0')
{
objHidden.value = objDropDown.value; //.substr(0,1);
//alert(" hdn = " + objHidden.value);
window.location = '<?=$MyPage;?>' ;
}
}
</script>
the dropdown's markup here,..then
<table width='100%' border='0' cellspacing='5' cellpadding='3'>
<?php
$Area = $_POST['txtSelection']; //or $_POST['hdnSelect']
which has zilch in it , even though it is set successfully by jvascript
Why is this such an issue in WordPress,
How do i overcome it.
It's nuts spending a full day on something which should be so trivial (works fine in a normal php situation, os asp or asp.net,..but not in WP.)!
TIA
N
This doesn't submit the form it just tell the browser to goto that page. Hence your value always empty.
window.location = '<?=$MyPage;?>' ;
Replace that line with this instead.
document.forms["frmSB_stores"].submit();