[英]How could I send a value to MYSQL from a dropdown selection without refresh page and without click the “send” button?
In a PHP page I have a simple selection with some values like this: 在PHP页面中,我有一些简单的选择,例如:
<div class="container">
<section>
<select>
<option value="" disabled selected>Select an activity</option>
<option value="1">1</option>
<option value="2">2</option>
...
</select>
</section>
</div>
I have a database MYSQL to store the choiced value
like this: 我有一个数据库MYSQL来存储选择的
value
如下所示:
table name= user_favorite
with 2 columns respectively called items
and values
表名=
user_favorite
带有两列,分别称为items
和values
items values 项目 值
item1 value1 item1 value1
item2 value2 item2 value2
etc. 等等
When a user select an item from the dropdown list I wish to send automatically to MYSQL the value
chosen (inside the values
column) without click on a send button. 当用户从下拉列表中选择一项时,我希望将选择的
value
(在“ values
列内)自动发送到MYSQL,而无需单击发送按钮。 Is it possible and how to achieve? 有可能并且如何实现?
As @NishantSolanki said, you should use Ajax. 正如@NishantSolanki所说,您应该使用Ajax。 Here an example using jQuery.
这里是一个使用jQuery的示例。
HTML FILE: HTML档案:
<div class="container">
<section>
<select id="options">
<option value="" disabled selected>Select an activity</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</section>
</div>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#options").on("change", function(){ //listen when the option change
var optionValue = jQuery(this).val(); //get the new value
$.ajax({
url: "fileWhichSaveTheValue.php", //php file which recive the new value and save it to the database
data: { "newValue": optionValue }, //send the new value
method: "POST" //use POST method
});
});
});
</script>
PHP FILE: PHP文件:
$newValue = $_POST["newValue"]; //if you used POST method on the javascript, you have to use $_POST here to get the data
//HERE YOUR MYSQL CONNECTION AND YOUR QUERY FOR SAVING THE VALUE
Use onchange event on select 在选择时使用onchange事件
<?php
if($_POST){
$item = $_POST['item'];
$link = mysql_connect('host', 'username', 'password');
mysql_select_db('database_name', $link);
//write your sql query to enter into table
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<div class="container">
<section>
<select onchange="save_record(this.value);">
<option value="" disabled selected>Select an activity</option>
<option value="1">1</option>
<option value="2">2</option>
...
</select>
</section>
</div>
<script type="text/javascript">
function save_record(item){
//call an ajax here to post item
$.post( "your_php_page_name.php",
{item:item},
function( data ) {
// do something after ajax result
});
}
</script>
On your php page you can retrieve post data by $_POST
variable 在您的php页面上,您可以通过
$_POST
变量检索发布数据
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.