Can i echo hidden field under <select> - php

I do not know if it makes sense but i am trying to echo a hidden field in select box but does not work. How can i echo
echo "<input name='testt' type='hidden' id='testt' value='".$ver["cats_fee"]."'>";
in here:
<select size="1" name="parentcat">
<option value='0'>---- Top Category ----</option>
<?
$al=mysql_query("select * from cats where cats_parentid='0' order by cats_id desc");
while($ver=mysql_fetch_array($al))
{
echo "<option value='".$ver["cats_id"]."'>".$ver["cats_name"]."</option>";
$al2=mysql_query("select * from cats where cats_parentid='".$ver["cats_id"]."' order by cats_id desc");
while($ver2=mysql_fetch_array($al2))
{
echo "<option value='".$ver2["cats_id"]."'> > ".$ver2["cats_name"]."</option>";
}
}
?>
</select>

It looks like you're trying to send multiple pieces of data based on a user-selection. It's easier just to send the unique id (as you are already doing) then lookup the 'fee', along with any other data you need' in the script that the form sends to.
As an aside, it also looks like you are making many database calls to, effectively, get all cats back. If that's true, it's probably more efficient to just get them all with a single call and handle the hierarchy in your script.

Because both the select box, ancd an input field are form elements, you can't nest them. But because you only use hidden input fields for storing data on your page, out of sight for the user, it doesn't really matter where you place it, as long as it's inside the form.

You can't see which option the user is selecting on the client side when you are at the server side. The solution is using javascript - which is a client side language, search like this or this would help alot I think.

Related

Possible to run DB update function when dropdown is selected

I would like to know if it would be possible to run an update query when an item is selected from a drop down list. The user makes a choice, a function is then called to update a particular field in a database. This will be achieved using a select box to store the options. Thanks.
echo '<td>';
echo '<select name="order_status[]" onChange = "update()">';
echo '<option value = "1" class ="pending">Pending</option>';
echo '<option value = "2" class = "approved">Approved</option>';
echo '<option value = "3" class ="disapproved">Disapproved</option>';
echo '</select>';
echo '</td>';
echo '</tr>';
Yes, it's possible. If you want the query to be run seamlessly (that is, without a submit button being pressed and the page refreshing), then you'll need to use Ajax to send the request asynchronously to your PHP script.
EDIT: The easiest thing to do is simply use jQuery's $.get() functionality in your onchange event. That way, each time someone chooses an option, jQuery will send the request to your PHP script with that option's value. The PHP script will run, and return the new data back to your jQuery, which will then use its DOM functionality to insert that data into your page.
You can do the same thing with a button. Just stick $.get() in the button's onclick event rather than in the select element's onchange event.
The jQuery site's documentation will give you relevant code examples.
EDIT 2: Okay, here's a very canned example.
First, let's think about the actual process you want to have happen on the back end. In the simplest terms, you want to take an id from user input and use that to run in a query. Pretty straight forward (using PDO for the database work):
// in a real app, you'd need to sanitize and validate the incoming id
$id = $_GET['id'];
$stmt = $dbh->prepare("SELECT * FROM table_name WHERE id = :id");
$stmt->bindParam(":id", $id);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
echo json_encode($row); // makes it jQuery friendly
Okay, so the back end is pretty simple. Now, for the font end, where the magic happens. Here's how I'd approach using both a select element and a button in order to pass the id back to the PHP script, and then handle the results:
<!-- Your HTML up to where the select and button are on your page -->
<select id="id" name="id">
<option value="1">Something</option>
<option value="2">Something Else</option>
<option value="3">Yet Another Thing</option>
</select>
<button id="btn" />
<!-- In your jQuery -->
$("#btn").click(function() {
$.get("path/to/your/back/end/script.php", { "id" : $("#id").value }, function(data) {
/* the data will be the json_encode($row) that was echoed from the PHP script.
* so, you'll need to drill into it, take the data you want, and use
* jQuery's/JavaScript's DOM manipulation tools to insert the data on your
* page
*/
}) // close $.get()
}); // close .click()
None of this is tested, and it's admittedly incomplete, but that should be more than enough to get started. Really, all you'll need to figure out is how to drill into the returned data (it's a JSON object, so it shouldn't be too bad... use a browser's web development tools to see how the data is actually formed) and insert it where you want. That, and any dumb errors I may have made above.
Hope this helps!

Create <select> elements on the fly and send multiple POST as an array using jQuery and PHP

I wonder if it's possible to populate <select> elements with option values generated by PHPto a page (after load) whenever a user is clicking a button withid='add'and then be able to store each value selected as an array then send this via $_POST to a PHP page?
I would like to populate the <select> element like this:
/theloader.php
echo "<select class='plan_id'>\n";
while ($row = mysql_fetch_array($course_elements)) {
echo "<option value='".$row['plan_id']."'>".$row['plan_name']."</option>\n";
}
echo "</select>\n";
?>
This will output
<select class='plan_id'>
<option value='1'>Description</option>
<option value='2'>Description</option>
<option value='3'>Description</option>
</select>
Then when the user has populated the needed elements and selected values, click save and send everything to anotherfile.php:
$("#save").click(function() {
// Store each value as a variable then send to /anotherfile.php
});
I lack knowledge in how to perform this kind of action and would really appriciate som tips in the right direction.
Thank's in advance.
Is there any reason the population of the selects has to be dynamic? Does the data change, or are you just letting the user add more line items to choose from pre-set options?
If the data in the dropdown itself is dynamic, you will need a combination of javascript and ajax calls to get the data from the php in real time.
If the options are not dynamic, then you do not need ajax at all, just populate the variables in javascript and create an action to add more dropdowns using the already defined variables.

Get data from another table inside of returning data

I am having trouble figuring out how to implement this. I am returning user data to populate a profile page where the user can edit information. It fills in fields like name, job, title, etc. I have a field called Interests where I grab the Main Interests before I execute the code returning the user data. So I store those in an array and then return them to populate the first one. But the second is dependent on which choice they make. How should I go about filling that second box (I know the code that I will use I asking about how I should store the data to be retrieved. Because I cant execute a sql command inside the while loop, and I dont really want to return every sub-interest that just seems like a waste of resources)
Code for returning user data:
$result = mysql_query("SELECT * FROM WHERE U.uid = '$uid';");
while($row = mysql_fetch_assoc($result)){
Code for Adding Interests:
<option selected value="">Select an Interest</option>
<?
for ($i=0; $i<$setintcount; $i++)
{
if($setinterests[$i] == $interests[$i])
{
echo "<option selected value='$setinterests[$i]'>$setinterests[$i]</option>";
}
else
{
echo "<option value='$setinterests[$i]'>$setinterests[$i]</option>";
}
}
?>
</select>
Sub-Interest: <select name="selectedsubint" id="selectedsubint" onchange="checkval(id);">
<option selected value="">Select an Sub-Interest</option>
</select>
The easiest way is load all sub-interests, but you wrote its waste of resources. It depends on how much sub-interest you will have stored.
Another solution is to refresh page and get needed sub-interests, but it seems rough to me.
Elegant solution could be by using AJAX to get sub-interest. Throu AJAX you could call page that will generate right sub-interests for selected main-interest.

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