Reputation: 1242
I have no idea where to begin, so if there is already an answer out there to a question like mine I would appreciate it! Basically the question says it all, Here is what I would like:
There is a drop down menu, simple drop down menu, nothing fancy. When a selection is made in that drop down menu, a php mysql query is ran where the database will be updated with that value. I have all the pieces, all I need is the code that would be able to kick it all off.
For instance when you hit submit on a form you would typically type out:
if (isset($_POST['submit']))
{
//grab information and insert into db
}
How would I do this for a drop down selection without having to click the submit button.
Upvotes: 0
Views: 4579
Reputation: 2750
you should be looking for something like this
<form id="testform">
<select id="yourselect" name="yourselect" onChange="updateDb()">
<option value="somevalue">Please select</option>
<option value="somevalue1">Something</option>
</select>
</form>
you Javascript function will look like this
function updateDb() {
// I am using jquery for ajax
$.post("yourserverhandle.php", $("#testform").serialize());
}
and this is how your "yourserverhandle.php" looks like
<?php
$query = "update yourtable set something='".mysql_escape_string($_POST["yourselect"])."' where id='something'";
.... mysql connect, execute
?>
Upvotes: 1
Reputation: 65264
As has been said in the comments, you listen to the onchange
event of the selectbox and either submit a form or use AJAX. This is not my point.
From a usability POV I recommend you reevaluate this proposition, if it really leads to a database update: Ever used the mouse wheel to scroll, while accidently having the focus on a selectbox? Jackpot! You just changed your DB settings without being aware of it.
So using onchange
on a selectbox to kick off something, that is immediately visible is IMHO a good thing - you'll know, when you triggered it. Changing a DB setting with no feedback other than the select box changing value is IMHO a bad thing. Or an accident waiting to happen.
Upvotes: 3
Reputation: 31033
$("#DDL_ID").change(function(){
$.ajax({
url:'/some.php',
type:'POST',
data:{submit:$(this).val()},
success:function(data){
//do something here if the server return anything
},
error:function(){
console.log("something bad happened");
}
});
});
on the php side
if (isset($_POST['submit']))
{
//grab information and insert into db
}
P.S. always sanitize the input see mysql_real_escape_string
Upvotes: 0