Processing a form with multiple multiple selects - php

I have a form for registering people to events, while the user can add or remove registered people - the number of inputs is dynamic.
Now, the regular inputs are easy to process, it's just
<input type="text" name="first_name[]">
And I process it as an array in a loop for each participant.
However, I need to have a multiple select input for each person, like
<select multiple name="extras[]">
<option value="42">Some extra feature</option>
...</select>
But that of course puts all the selected options into one array and I can't recognize which user picked which options.
I also tried name="extras[][]", but that just puts each value into a separate array.
How can I make the form/the PHP script a way that I can tell who chose what?
Thanks

send user specific info with option value like
<select multiple name="extras[]">
<option value="42###USER_ID">Some extra feature</option>
</select>
then explode it on your php script like
foreach($_POST["extras"] as $a->$b){
$userAndExtras = explode("###",$b);
$userId = $userAndExtras[1]; // gives USER_ID
$anotherValue = $userAndExtras[0]; // gives 42 or something like that
}
--
or use hidden fields

Related

PHP I need to get the numerical value="" and what the user sees

So I'm using a form with the POST method and I have no trouble getting the value="" of the option chosen by the user. Got my math working and everything, no problem. Then I'm going over everything and realized that I need to show the user their Dilution Ratio, for example 1:1, based on what they chose.
<select name="yourDilution" id="yourDilution">
<option value=""></option>
<option value="2">1:1</option>
<option value="3">1:2</option>
<option value="4">1:3</option>
<option value="5">1:4</option>
So how do I get that done?
Thank you for your time.
Oh and please no .js, that language and I aren't currently on speaking terms.
You have a couple options:
1 - Pass the value you need
You can simply pass '1:1' as the value and make your form handler based on this so that it is available for outputting later.
<option value="1:1">1:1</option>
2 - Use logical values
You could also simply pass the defining part of the ratio. If all the ratios are 1:x then pass the value of x and know that the resulting ratio will alway be 1:x
<option value="1">1:1</option>
Then in your form handler
$display = "1:".$_POST['yourDilution'];
3 - Use value like an ID
Re-define the value and display value relationship in your form handler with a switch statement
switch($_POST['yourDilution']){
case 2:
$display = "1:1";
break;
//etc ...
}
Personally, I like Option 2 since it's simple and allows you to pass the least amount of data and requires less work if the form values change. Hope this helps.
You can simply handle this with using a array example,
<?php
// Here you put your options value that you want to show the user
$array = ["1:1","1:2","1:3"];
// Here you get the selection value of the user
$postValue = 2; // in your case $_POST['yourDilution']
// here you show it to the user
print_r($array[$postValue]);
?>

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 ].

Trying to dynamically add options to an array of HTML select fields Php/AJAX/jQuery

I have an HTML array of 10 select fields that must be populated by jQuery each time the div-popup is called. (Each one gets the same options) We have periodic needs for hundreds of employees and this form is intended to allow requests staffing to be forwarded to upper management for approval in a batch fashion by department. I’ll be using .serialize to submit the form but I am unclear as to how to initialize this element with the proper information for input selection. All the info I could find was about submitting the form array, which I already knew how to do.
Here is the HTML structure:
<select id="detJobsCR[]" name="detJobsCR[]"> </select>
And here is my attempt to populate the selection fields:
$.post("events.php",{a: 'detadd-joblist', dept_id: deptID}, function(data) {
for(var i=0;i<10;i++){
$('#detJobsCR[i]').html(data);
}
});
(I tried explicitly defining each elements array position [0],[1]..etc and that did not help.)
The data returned is simple HTML like:
<option value='38'>Admin Support Assistant I</option>
<option value='39'>Admin Admin Support Assistant II</option>...
Thanks for whatever assistance you can offer!
FYI Update: Musa's answer worked perfectly. I also had issues with Date & Time pickers not working, it turns out, for the same reason. When I converted them to classes I was able to use this(below), and the are all now working as well:
$(".detDateStart").datepicker();
Ids should be unique so each select should have its own id. If you want to have one identifiier to represent all the selects you could use a class e.g. <select class="detJobsCR" name="detJobsCR[]"> </select> and then select them with $('.detJobsCR') and set their html with .html(data)
$.post("events.php",{a: 'detadd-joblist', dept_id: deptID}, function(data) {
$('.detJobsCR').html(data);
});
Your problem is two fold:
You're putting i inside your quotes, so it's not interpreting the value of the variable i
Even if i wasn't inside the quotes, when jquery parses the [i] in the expression it's looking for elements with id detJobsCR and with attribute i defined.
Since you have only ONE element, with ID detJobsCR[] you would query it like this: $('#detJobsCR\\[\\]') You need to escape the [ and ] character so jquery knows it's a part of the ID and NOT a parsing rule (for parsing/looking for an attribute).
As suggested by Musa, you can make your life much easier by using a simple class name that doesn't require escaping values. But if you do want to select by id, the example above should do the trick.

Is there anyway i could dynamically fetch the value of an <option> and pass it to PHP without using AJAX?

I have two <select> one is category and the second is subcategory.
here is the first <select> for category.
<select name="category" size="10">
<?php foreach($categories->fetch(array('table' => 'categories')) as $category) { ?>
<option value="<?php echo $category['id']; ?>"><?php echo $category['name']; ?></option>
<?php } ?>
</select>
now the second <select> i.e subcategory should be hidden initially and when a user click on category <select> based on the value it should populate the value in subcategory.
One way of doing this is via AJAX by passing categoryId as POST Request and getting HTML as response.
however i would like to know if there is any other alternative so that it automatically pass the categoryId value to PHP and unhide the second <select> here is the code of second <select>
<select name="subcategory" size="10">
<?php foreach($categories->fetch(array('table' => 'subCategories', 'categoryId' => $categoryId)) as $subCategory) { ?>
<option value="1"><?php echo $subCategory['name']; ?></option>
<?php } ?>
</select>
the only thing i need here is $categoryId to be populated dynamically. is there any way of doing this?
thank you..
No, there is no way to do what you are suggesting. PHP is only run on the server, so by the time the page is rendered on the client the PHP has already been run.
Your best bet would be what you already suggested, running some AJAX after the first select is changed, sending back the category ID to the server and retrieving what you need to build the second select.
Is there a reason why you don't want to do it this way?
Sukumar has probably suggested the best and most intuitive solution to make it appear as if the data is being loaded dynamically to the user.
The other alternative would be to submit the form when the select box is changed. Once the form has been submitted PHP would pick up the ID from the POST array and then re-populate the sub-category select box. This is often used as a fallback in case the user doesn't have JavaScript enabled.
Structurally, there are three choices to solve this problem:
Use an ajax call to fetch the required data when a user selection is made as jbruno has described.
Submit the whole page to the server, let your PHP see the newly selected option and fill in the newly desired data in a returned page. This will cause the page to refresh so is less ideal than option 1.
Pre-populate the page with all possible data in a javascript data structure so you can use Javascript to just look up the desired category ID in a local data structure, modify the page and never have to talk to the server in order to update the page.
In my opinion, option 3) is the most desirable if the data set required for local lookup is not too large (say under 100k) and it's not too expensive on the server to collect all that data for inclusion in the original page and if the data doesn't change real-time or having data as of the page load time is OK.
If option 3) isn't feasible for any reason, then option 1) is next best. Option 2) is not as good a user experience so it should only be the last resort if you really can't implement options 1) or 3).
You asked more specifically about option 3. I don't really yet understand what the whole data you need looks like. If you really only have four total data types residential_plot, residential_apartment, office_space and showroom, then you can just make those be four keys on an object and store their data that way:
var data = {
"residential_plot": 1,
"residential_apartment": 2,
"office_space": 3,
"showroom": 4
};
The 1, 2, 3 and 4 are just whatever data you want to store for that type. It can be numbers, strings, arrays of data, other objects of data, anything.
To access this, you would do like this:
var id = data.residential_plot;
or
var index = "residential_plot";
var id = data[index];
If you wanted to store the notion of categories and sub-categories, you would need an extra level of objects:
var data = {
"residential": {"residential_plot": 1, "residential_apartment": 2},
"commercial": {"office_space": 3, "showroom": 4}
};
Then, you would access it like this:
var id = data.residential.residential_plot;
or like this:
var category = "residential";
var catType = "residential_plot";
var id = data[category][catType];

How do you set the default value of a drop down list that is being called via AJAX from another page?

For my code, my drop down lists are initiated on the original page, via
<select name =country id=country
onchange=showRecords(this.value,'country','province')>"
This function is taking the value, equating it to country, then querying MySQL, and setting the results where id=province, and creating cascading dropdown lists. This is obviously via Ajax.
So, when $_REQUEST['province'] is set, then the Province dropdown list gets populated with all provinces from the country to which it belongs, etc.; i.e.;
<?if(isset($province)){
echo "<script>showRecords('".$country."','country','province');</script>";}?>
However, for the life of me, I cannot figure out how I can set the default value equal to $_REQUEST['province']. I cannot use the traditional way:
if (($selected) == ($value)) {
$options.= " selected";
}
Because it is querying the AJAX page with one piece of information at a time.
Any ideas would be greatly appreciated.
Your code doesn't seem to make a lot of sense. The particular thing that worries me is that you say ajax is loading one item at a time?
Perhaps something like this. A country select tag like...
<select onchange="showRecords(this)">
As well as creating the javascript function showRecords() which will be called when someone chooses an option in the select tag.
<script>
function showRecords(calling_element) {
// do AJAX call here using calling_element.options[calling_element.selectedIndex].value as the selected country. this.value does not work for select tags.
}
</script>
the PHP page that receives this AJAXed request would reply with a JSON object containing all of the province values, or a delimited list.
once the Javascript showRecords function receives the responce from the PHP page, it would add each of these options to the correct select tag. Once finished, it would set the default value to whichever option it wants by something like the following:
target_element.selectedIndex = {desired list index here};
I have a lot of assumptions to your questions,
first is, if bydefault you have the select province like this
<select id="province">
<option value=""></option>
<option value="California">California</option>
<option value="Washington">Washingthon</option>
</select>
then you can use this script to default select
document.getElementById("province").value="Washington";
but if bydefault you have the select province like this
<select id="province"></select>
then you can use this script to default select
document.getElementById("province").innerHTML='<option value="Wahsington">Washington</option>';
so it depend on your code and your need. maybe if you have another case the problem should be solved in another way.
cmmiiw :)

Categories