Reputation: 948
Good morning!
I know that this topic has been covered on SO before but I couldn't find the full answer to my specific situation below so I apologize if I missed the answer elsewhere.
Scope:
What I am trying to achieve is a drop down list (either done with pure HTML or java script, HTML is preferred) that can load a php file. Inside that php file it should be able to access the selected drop down's value.
What I have tried:
Method 1:
I have used a method like this before:
<form action="test.php" method="post">
<select name="dropdown" id="dropdown">
<option value="value1">Option 1</option>
<option value="value2">Option 2</option>
</select>
<input name="submitbutton" type="submit" value="submit" />
</form>
Then clicking on the submit button, the test.php page loads and I can get the value of the dropdown using $_POST("dropdown"). This method works perfectly fine! However I want to submit the form WITHOUT need of the button, simply using the drop down onchange event instead.
Method 2:
I also tried using:
<form>
<select name='dropdown' onchange='this.form.submit()'>
<option value="value1">Option 1</option>
<option value="value2">Option 2</option>
</select>
<noscript><input type="submit" value="Submit"></noscript>
</form>
which will reload the page onchange but not the test.php page.. Changing "this.form.submit()" to test.php doesn't work.
I feel like I am close with both but not quite there. I hope what I am trying to achieve is explained well enough.
Thank you for any responses ahead of time!
Upvotes: 8
Views: 58128
Reputation: 237
Try using with ajax
jQuery:
$(document).on("change", "select#dropdown", function(){
$.ajax({
url: 'http://localhost/test/action.php',
type: "post",
data: $("#myform").serialize();,
success: function(response) {
$('select#dropdown').after("dropdown changed!");
}
});
});
Upvotes: 0
Reputation: 7302
You forgot to add 'action="test.php"
' and 'method="post"
' in your for tag.. So, your IInd method should like below:
HTML Code:
<form action="test.php" method="post">
<select name='dropdown' onchange='this.form.submit()'>
<option value="value1">Option 1</option>
<option value="value2">Option 2</option>
</select>
<noscript><input type="submit" value="Submit"/></noscript>
</form>
and it will work and you can show your post data with print_r($_POST)
in test.php
. It will show you dropdown
value :)
Upvotes: 0
Reputation: 114347
Give your form a name:
<form name="form1" action="test.php">
....then your onchange would be: document.form1.submit();
BTW, this has nothing to do with PHP, since it is 100% on the client.
Upvotes: 3
Reputation: 697
Add:
<form action="test.php" method="post">
To method2 and it should work fine.
Upvotes: 7