Autofill form when link is pressed - php

I have this webpage. It has a page called "services.php". I have several buttons (made of classes), that belong to different "package" prices i offer.
I want the links that say "Select" to autofill a form in another page, or alternativly in a popup form in the page..
I don't really know how to explain it, but as short as possible:
When link is pressed autofill form (in this or other page) with the type of package they chose. Only text autofill

What you seem to be asking is 'loading' a page pre-filled with specific information, you can do this a number of ways, either by utilizing javascript (like jQuery for instance). Or using your PHP, make links that pass variables (say a flag or a reference to pre-fill the fields -- if you want a popup or next page, etc).
Your url would like like the following for the button that a user presses (button would be a simple http link):
http://mywebsite.com/prefill.php?user=bob&package=2
This would have the values bob as the user that requests it (you can reference an id for user info here as well), and package=2 to designate your package options.
Then on the prefill.php page, you would have something that checks for:
$user = $_GET['user'];
$package = $_GET['package'];
Hope that helps

This will populate form fields with whatever you pass to the autoFill() function. This would be a same page example.
<html>
<body>
<form>
<input type="text" id="packageDescription">
<input type="text" id="packagePrice">
</form>
<script>
function autoFill(packageDescription, packagePrice) {
document.getElementById('packageDescription').value = packageDescription;
document.getElementById('packagePrice').value = packagePrice;
}
</script>
Premium Package<br>
Platinum Package
</body>
</html>

You could do something like this:
<select id="packages">
<option value="package1">Package 1</option>
<option value="package2">Package 2</option>
</select>
Submit
When the link is clicked, the following javascript will fire off:
function submitPackage()
{
var package = $("#package").val();
window.open("http://your-site.com/some-script.php?package=" + package);
}
The above will open a pop up window to a page such as this:
http://your-site.com/some-script.php?package=package1
In some-script.php you will do something like this:
You selected the package: <b><?php echo $_GET['package'];?></b>.
Or:
<?php
//Put the packages in an array:
$packages = array();
$packages['package1'] = 'Package 1';
$packages['package2'] = 'Package 2';
//...
?>
<select id="package">
<?php foreach ($packages as $name => $text):?>
<? $selected = ($name == $_GET['package']) ? 'selected' : '';?>
<option value="<? php echo $name;?>" <?php echo $selected;?>>
<?php echo $text;?>
</option>
<? endforeach;?>
</select>
The above will auto select the package they selected in a dropdown box.

if i understood your problem, you want to fill some input fields with information when the user clicks on some links
i can think of 2 ways of doing this : either have the links point to a page like services.php?req=package1 (or any other url you want) and on that page generate the input fields with the information you need (set the default values in the fields with the ones you want), or, use javascript to change the values of the forms without changing the actual page (either via ajax or predefined values)
for javascript you can use the jQuery framework, it has a pretty extensive community of enthusiasts and plenty of examples to get you started with it.
an example for your case would be
$('#btn1').bind('click', function() {
$('#input1').val("value");
$('#input2').val("value2");
});
replace btn1 with the id of the first button or link you have, input1 with the id of the first input in your form, and value with the value you want

I just did this myself. My solution was with jQuery. Just assign an id to your link. The first ID in the code is the link id and the second is the id for the input element you want to populate.
Here is the script:
<script>
$(document).ready(function() {
$('#link_id').click(function() {
$('#input_id').val( $(this).text() ).keyup();
return false;
});
});
</script>
Hope it works!

I've ran several time into the same issue, so I had to write my own script doing this. It's called Autofiller and its pretty simple but does great job.
Here is an example
http://example.com/?autofiller=1&af=1&pof=package&package=package1
So basically it takes several parameters to init the script:
autofiller=1 - init AutoFiller
af=1 - Autofill after page is loaded
pof=package - Find the parent form element of the select with name attribute package. Works also with input form elements.
package=package1 - Will set the select element's value to package1
Hope it helps you! :)

Related

Keeping some selected options after submitting form

Thanks in advance for any suggestions on the following:
I've created a php-page to add works from composers to CDs in a database. It's a combination of two forms and looks like this:
1st form:
Composer : [drop down list] : Select
Some blank space
2nd form:
Title : [drop down list]
Track number : [empty varchar field]
Work : [drop down list]
some other fields
Process button
After selecting a name in the first block (posting to $_SERVER["PHP_SELF"]) I stay on the same page, that name is shown in the blank space in between and the drop down lists are populated with only CD titles and works of the selected composer.
I can then select from the lists and enter other data in the other fields. Hitting the process button posts the data from the second block to another page which will eventually send everything to a table in a MySQL database.
After that I send myself back to the first page with header("Location: the_first_page.php")
So far so good, but upon returning I would like the composer, title and work to be preselected. Now I'm sent to a blank page and have to start from scratch. I think I've seen some solution involving testing $_POST['something'] against <option value> in a drop down list but I can't seem to make that work.
My question is: Is there a way to send $_POST['Title'] and $_POST['Work'] back to the first page somehow? Or is it better to split the two forms over seperate pages?
All help is welcome.
You could use sessions or the post data itself. For using the post data itself, the page where you send the request should be the same and include the script that will process it if there's some data like this:
if (!empty($_POST)) {
include "save.php";
}
// More code...
?>
<select name = "a">
<option <?php if ($_POST['a'] == "test") echo "selected"; ?> value = "test">
<option <?php if ($_POST['a'] == "testb") echo "selected"; ?> value = "testb">
</select>
Of course there are many more ways, but this is just a simple one to get you started. Things to know: you might want to change the variable $_POST and clean it up before using it. In this case it should be fine, but in <input type = "text" value = "<?= $_POST['b']; ?> name = "b">` you have a serious security issue.
For sanitizing the input, you want to sanitize it respect to what you expect. But also, as an EXTRA meassure, you normally want to strip everything that looks like a <script>, onclick ="", ' DROP TABLE users and similar. It's not an easy subject, so I recommend you reading on it, mainly on the XSS attacks which is relevant to showing the text back to the user. While it might seem too much work for this "simple case", it is useful in many more situations.
Use session variables and put conditions for them ... see [ $_SESSION ].

drop down changes from other drop down with calculation. Jscript / Ajax?

I have a Jscript Query.
I have done a bit of reading and found out that AJAX is just a side server for a lfash script that can be used on Linux with php. (please correct me if I have interperated that wrong)
I have no knowledge on how scripts work so this is new, I have tried a couple of different tries but no luck.
I have one drop down box (Box1) (populated from Database)
I have another box (Box2) for a calculation to insert into my database for other uses on ohter parts of hte site.
I need the Box2 to change the figure when someone changes Box1 dropdown before hitting the submit button.
I think because I have the calcualtion this is getting me stuck... Code is as below... Can someone please help me figure out (I think I need some form of Script to do this.) the answer...
Box1
<td><p>selection 1</p>
<select id="t1_type" name="t1_type">
<?php $result = mysql_query("SELECT * FROM `t2` ORDER BY t2_value");
while($valuerow = mysql_fetch_array($result)){
echo '<option value="'.$valuerow['t2_name'].'">'.$valuerow['t2_name'].'</option>'; } ?>
Box2
<input name="t1_value" id="t1_value" value="
<?php
$var1 = $row_value['t2_value'];
$var2 = $row_dropdown['t1_number'];
$total = round ($var2 * $var1);
echo "" . $total . "";
?>" />
I hope this is all the code you need, (Let me know if more required)
What it needs to do is show new calculation whenever someone changes the box1 option BEFORE the submit button is clicked, so it submits the correct calculation to the database for future use.
I think it would need pretty much "t2_value" from box2 to change when ever "t2_name changed from box1.
And once again the best link to learn about the solution. (Learnt about Joins now from my last question!! Almost a intermediate user. ;-) )
Edit :
I saw that your second box was a textbox I believe, if thats the problem then you should do something like this
<select id="t1_type" name="t1_type" onchange="change(this);">
<?php
$result = mysql_query("SELECT * FROM `t2` ORDER BY t2_value");
while($valuerow = mysql_fetch_array($result))
{
echo '<option value="'.$valuerow['t2_name'].'">'.$valuerow['t2_name'].'</option>';
}
?>
</select>
This defines your <select> box like you did in your question.
Add an onChange event into your first <select> and then create a function to handle to onChange event. An onChange event fires whenever the user changes the item in the <select> element.
Javascript :
( put this part of the code above the </head> )
<script language="javascript" type="text/javascript">
function change(element)
{
// do here whatever you want
// you can change the value of the <input> box with :
// document.getElementById(element.id).value = your_value
// If you want to see if this part works, then try adding this :
// alert("It works!");
// If you want to get the text of the item which has been selected in Box1 use :
// $("#t1_type option:selected").text();
}
</script>
Note: because PHP is server side, you can't update your Box2 dynamically without a page refresh, Javascript however is Client Side and CAN do this.
Note : the $("#t1_type option:selected").text(); code requires you to include the jQuery library into your script. Be sure to convert this variable to a float, int or double if you want to calculate with it, else the outcome will give NaN (Not a Number)
Tutorial on including jQuery Libary :
http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery
If you're new to JavaScript, you should try some tutorials. The ones at w3Schools.com helpt me alot, but some people say they're not always correct, but anyhow, read some stuff about Javascript to actually know what you are doing, instead of copypasting code :)

How do I hide a form field?

How do I hide a particular form field when a field is selected from a drop down in HTML?
You can't use php, as content has already been served to browser. So, a handy solution is to use javascript
<select name="foobar" onchange="checkAndHide(this.options[this.selectedIndex].value)">
<option value="right1">right1</option>
<option value="wrong">wrong</option>
<option value="right2">right2</option>
</select>
<input type="text" id="shouldHide" name="test">
<script type="text/javascript">
function checkAndHide(value){
if(value == 'wrong')
document.getElementById('shouldHide').style.display = 'none';
else
document.getElementById('shouldHide').style.display = 'block';
}
</script>
Yes you must use something that can communicate with the header which requires JavaScript or jquery, etc.
I don't have an example as I'm at work but I used jquery to load another page after a category is selected. This page generates the rest of the select fields (my sub categories) using a query and while statement ,inside the option tag once a category has been picked. There are many examples on google, just google jquery dynamic dropdown box

How to get selected index of dropdown from PHP post

I have an HTML form which contains a drop down, a tinyMCE textarea, and a save button.
The dropdown is used to select a file to edit.
I load up the required file into the tinyMCE editor by making an ajax call when the jquery change() event is triggered from the dropdown. That works fine.
The problem I'm having is saving the file off. I am trying to do it by posting the form off to another php page which will write to the file and then send us back to the main page.
This is the php code within my writeFile.php page:
<?php
session_start();
if (!isset($_SESSION['id'])) {
header ('Location: index.php?error=0');
}
else {
if (isset($_POST['save'])) {
$text = $_POST['mceContent'];
$index = $_POST['files']; // << PROBLEM LINE!
$array = array('homeText.txt', 'anotherText.txt');
$fileName = $array[$index];
$path = '../txt/'.$fileName;
$length = strlen($text);
echo "INDEX: $index"; // TO TEST THE INDEX VARIABLE.
$fh = fopen($text,'w',true);
fwrite($fh,$text,$length) or die('Could not write');
fclose($fh);
header ('Location: admin.php');
}
}
?>
The $index variable is meant to be the selected index in the dropdown, however it is posted by my form as the selected string value in the dropdown.
I can think of three solutions (ordered from least likely to work to most likely)
There is some way to get the index from that php post?
I can make a change in the HTML form/select tag to tell it to post the index and not the value string
I change it to a jquery event, with the on-click, and pass in the index to a post manually with xhr.
If someone could help me with implementing one of these method that would be great.
If you have your own, better solution I would be happy to hear that as well.
Also note that I can't build the path from the value string, because my dropdown uses descriptive strings, not actual file names.
Thanks in advance, bear in mind I'm new to php and especially jquery.
I am not sure why you can't use the value attribute - the descriptive string would be the text portion of the option element, the filename to save could be the value:
<option value="path/to/file_to_save.php">Descriptive file name</option>
Doing it that way, the user sees the descriptive text, the server gets a useful bit of information it needs when the form posts.
If that is not an option, you could add an onSubmit event to the form in which you pass the selectedIndex property to a hidden form field, then return true and let the form submit normally.
Form snippet
<form onsubmit="return beforeSubmit()">
<input type="hidden" name="file_index" value="" id="file_index_fld" />
<select id="file_name_dropdown">
<option>...</option>
Javascript snippet
var beforeSubmit = function () {
$('#file_index_fld').val($('#file_name_dropdown').attr("selectedIndex"));
return true;
}
... now in PHP's $_POST variable, you'll see $_POST['file_index'] contains the selectedIndex of the select element.
The long and short of it is that the selectedIndex property is a DOM item and not part of the POST data. No matter what, you are either going to have to intervene with javascript to add the data to POST, or modify your option elements to pass the desired data. I would always lean toward the former route as it is less complex.
Another option I can think of: Before posting, catch the new index in the change-event and write it to a hidden input-field of your form. After that, you can serialize and post it with jQuery.

Problem with keeping selected value in form after reloading page

I'm trying to populate a second dropdown in a dynamic way based on a previs selected dropdown.
However, I've managed to write get the page to reload when I choose anything in the dropdownbox but the chosen value isnt passed after reloading.
I have register_globals turned off (and prefer to) and i'm using the GET function to submit the form. However when I try setting values in the URL I cant get it to work.
Example: dropdown.php?area=1 still gives me a value in the dropdownbox with the default value.
What am I doing wrong? Running on a LAMP server. Apache 2.2, php 5.3.
Note: I found the php code here on the web wwich is suppose to help me pass the GET variable and select the option in the selectbox.
This is my code:
<html>
<head>
<SCRIPT language=JavaScript>
function reload(form)
{
var val=form.area.options[form.area.options.selectedIndex].value;
self.location='dropdown.php?area=' + val ;
}
</script>
</head>
</body>
<? #$area=$HTTP_GET_VARS['area']; ?>
<form action="" method="get">
<select name="area" id="area" onchange="reload(this.form)">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
</form>
</body>
</html>
Also, if this could be done with POST (or equivalent function) it would be even better.
Regards.
I think you're not specifying anywhere which one of the options should be selected on page load. Depending on the value of $area, you should add something like
<option selected>1</option>
You could easily do this with a couple of lines of PHP when rendering the option nodes:
<? if $area == 1
print '<option selected>1</option>';
?>
etc.
Alternatively, you could just populate the second combo using client-side javascript eliminating the need for a page reload. If you need to do some sensitive server-side processing to calculate the value of the second combo, do it in a background AJAX call using jQuery (examples here). Postbacks for this kind of thing are kind of undesirable and old-fashioned these days.
Regarding the GET issue, if submitting the form has any side effects (eg. a change in state in the user's account, deleting something, creating a new entity) then it should definitely be a POST. Discussion here for example.

Categories