I have a simple dropdown menu and I would like to reload the page in order to submit a value via PHP $_POST WITHOUT clicking a submit button. Could I do this with javascript? if so, how?
Asked
Active
Viewed 4,933 times
1
-
2So when do you want the post to be triggered? On change of the dropdown? – Patrick Q Feb 21 '14 at 20:05
-
1Already answered here - http://stackoverflow.com/questions/7231157/how-to-submit-form-on-change-of-dropdown-list – Petar Sabev Feb 21 '14 at 20:08
4 Answers
4
AJAX is the answer. If you have jQuery in your page, use something like:
$("#mySelectBox").change(function() {
var selected = $(this).val(); //here you have the value of the selected option
$.ajax({
type: "post",
url: "myscript.php",
data: { value : selected } //this value will be accessible in your script via $_POST["value"]
});
});
EDIT
If you REALLY want to reload the page, although this seems a bit ugly since it might be uncomfortable for the user to select something in a dropdown list and having the page reloaded, jQuery can also make it very easy to do:
$("#mySelectBox").change(function() {
$("#myForm").submit();
}

lucasnadalutti
- 5,818
- 1
- 28
- 48
-
OP says "I would like to reload the page". While what you have is certainly more of the "modern" way to do it (and what I would suggest if starting from scratch), the OP may have a reason for wanting the reload. – Patrick Q Feb 21 '14 at 20:11
-
Actually I'm going to try to use this instead. I'm not very familiar with javascript. Where do i place this jquery script in my webpage? – user2799603 Feb 21 '14 at 21:05
-
-
Also, note that I assumed that your form id is "myForm" and your select box's id is "mySelectBox" ;) – lucasnadalutti Feb 21 '14 at 21:12
3
You'll want something along the lines of this…
<form id="myForm" name="myForm" method="POST">
<select id="mySelect" name="mySelect" onchange="document.getElementById('myForm').submit();">
<option value="optionOne">Option One</option>
<option value="optionTwo">Option Two</option>
</select>
</form>

Patrick Q
- 6,373
- 2
- 25
- 34
3
made a jsfiddle http://jsfiddle.net/9p7nc/
<form action="test.php" method="POST">
<select name="value" id="value" onchange="this.form.submit()">
<option value="blue">blue</option>
<option value="green">green</option>
<option value="red">red</option>
<option value="yellow">yellow</option>
</select>
</form>

Venkat Reddy
- 1,046
- 1
- 8
- 13
2
If you use jQuery you could do something like this:
<script type="text/javascript">
$(function() {
$('#yourSelect').change(function(){
$('#hiddenSubmitButton').click();
})
});
</script>

anders
- 202
- 1
- 3
-
Why would you do this instead of just calling the form's `submit()` function directly? – Patrick Q Feb 21 '14 at 20:17