Clearing a selected item from a dropdown using PHP - php

I used the code below to remove a selected item from drop down, but when I remove one, the other item pops up. For example, if these are my options: "guns, cars, money", as I select and delete guns, cars and money remains. However, if I select cars and delete it, the deleted guns options pops up again. It is frustrating.
<?php
$opts = array("guns","knives","ammo");
$selected = array($_POST['selectMenu']);
$revisedOpts = array_diff($opts,$selected);
?>
<form method="post">
<select name='selectMenu'><?php
foreach($revisedOpts as $v) {
echo "<option>".$v."</option>";
}
?></select>
<input onclick="array_diff()" name="Collect" type="submit" value="submit" />
</form>

PHP only acts when the page is loaded, and you load the same code over and over. In order for previously deleted options to stay deleted, you need some kind of data persistence (like a database). Otherwise, you can use javascript to manipulate the select options on the client side browser. Here is a good discussion
If you must bind the action to onclick() and receive the event on the server side, then you will need to use an AJAX call. The onclick calls a separate PHP script which deletes the option and returns some kind of success message.

you want to have a look at some js code to do this. look at something like that http://www.mredkj.com/tutorials/tutorial_mixed2b.html

use jquery
jquery auto suggestion

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!

Drop down live update in a form

How do you live update the content of drop down 2 based on the selection made in drop down 1 in a PHP based web form?
Would appreciate any code examples to work from.
Many thanks!
You are going to have to use AJAX, I would recommend jQuery's abstraction.
e.g.
<select id="sel1">
<option value="1">1</option>
<option value="2">2</option>
</select>
<select id="sel2">
</select>
<script type="text/javascript">
$('#sel1').change(funciton(){
$.ajax({url: 'fetchSel2.php',
data:{sel1:$('#sel1').val()},
success:function(data){
$('#sel2').html(data);
}
});
});
</script>
This presumes there is a 'fetchSel2.php' that is ready to serve the options for the second select.
e.g.
function getSecondOptions($sel1){
$r=mysql_query(RELEVANT_QUERY);
$opts='';
if($r && mysql_num_rows($r)>0){
while(list($label,$val)=mysql_fetch_row($r)){
$opts.='<option value="'.$val.'">'.$label.'</option>';
}
}
return $opts;
}
if(isset($_GET['sel1'])){
echo getSecondOptions($_GET['sel1']);
}
exit;
For live update, you need to use AJAX and require JS enabled browser. If the user-browser don't support JS or JS is disabled, the only option is to submit the form and reload the whole page with the updated option in the 2nd dropdown. If you want the JS code to perform AJAX, can you kindly tell me the JS library you want to use, so I can provide the code accordingly.
What you are looking for is a cascading dropdown list. This is done using AJAX triggered in sequence by each dropdown. Here is an example via Google (http://codestips.com/php-ajax-cascading-dropdown-using-mysql/), note I'm not endorsing this link, it's just the first reasonable result.
I recently did this with jQuery http://jsfiddle.net/tBrXt/1/
You have these options:
Use AJAX if you don't want the form to refresh and update parts of
the form.
If you don't want to use ajax and can bear with refreshing the whole
form, you can capture the onChange event of the drop down using
javascript.
If the user does not have javascript enabled, the above 2 methods
will fail. Therefore, it is best to include a button users can click,
which will ask the PHP side to rerender the form.
My personal preference is to use the last method as a fall back for those who do not have javascript enabled. Then use the first method (AJAX) to progressively enhance the form for those that have javascript.

How to handle event of selecting an item in <select> in html with jQuery?

<select id ="facetFilterList" class="ui-widget-content ui-corner-all" size="18" multiple="multiple">
So I want to trigger some event whenever the user clicks on an item and getting it's value as well.
$('#facetFilterList').change(function () { alert($(this).val()); })
The PHP part is not important here , we are working on the client side here.
basically u can use jquery $.get or $.post to post the value from the listbox when the user click on and and update something else back.
if you will be more specific with what you're trying to do, i bet other SO-ers will be able to help you better.
but for starters, you can play with this.

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.

Enumerate all Check Box in PHP

I have web page in PHP which displays all records in a table. I want to add check boxes against all rows and user can check a check box to select a row and then submit the page. When the page is submitted I want to enumerate all check boxes and check whether they are checked or not, How can I do this?
You'll create your checkboxes like this:
<input name="rows[]" value="uniqueIdForThisRow" type="checkbox" />
<input name="rows[]" value="anotherId" type="checkbox" />
Then you can loop through them like this:
<?php
// $_POST['rows'] contains the values of all checked checkboxes, like:
// array('uniqueIdForThisRow', 'anotherId', ...)
foreach ($_POST['rows'] as $row) {
if ($row == 'uniqueIdForThisRow') {
// do something
}
}
?>
PHP docs on dealing with forms, see especially Example #3.
Creating the form
You can generate the HTML as follows:
<form [action, method etc]>
<table>
<?php
foreach($dataSet as $dataRow) :
?>
<tr>
<td>
<input type="checkbox" name="dataRow[]" value="<?=$dataRow['id']?>"/>
</td>
[Additional details about datarow here]
<tr>
<?php
endforeach;
?>
</table>
</form>
AFTER POST
look into $_POST['dataRow'] : this will be an array with values the IDS of your $dataRow, so using array_values on $_POST['dataRow'] will give you all the ids of the selected rows:
<?php
$checkedRows = array_values($_POST['dataRow']);
foreach($checkedRows as $row) {
// Do whatever you want to do with the selected row
}
You don’t have to check all checkboxes if they have been checked. Because only successful controls are send to the server. And a checkbox is only successful when it’s checked:
Checkboxes (and radio buttons) are on/off switches that may be toggled by the user. A switch is "on" when the control element's checked attribute is set. When a form is submitted, only "on" checkbox controls can become successful.
So you just have to look what checkboxes you get in the request at all. And if you want to use <select multiple>, take a look at How do I get all the results from a select multiple HTML tag? in the PHP FAQ.
if i were you... i wouldn't fight with altering html table structure.
you can handle that with Javascript frameworks like JQuery which is very effective solution for you. you deal only a few lines of JS code and you don't need exaggerate the html output (i guess it's probably long enough). about jquery there is a good source named visual jquery if you have never used that.
here is the way how to do that.
you dont need to edit inside the loop. you just only put an id to your table tag.
then add new column to your table with checkboxes inside.
then you can get the values of checkboxes & serialize them in to a hidden input. or you can handle selected rows with ajax easy. i think JS framework will work better.
normally i've added many links to post but it says it's not allowed for new users.

Categories