当我点击是或否按钮时,我想将db中的字段更新为1或0 ..
<td> <input type="button" onClick="save();" value="Yes">
<input type="button" onClick="save();" value="No">
</td>
此代码将视图页面中的按钮显示为是和否。现在,点击“是”按钮,我该怎么做才能保存在数据库中?
<div class="bit-4 pad-small" style="float:none;">
<br>
<br>
<?php echo $this->Form->input('approve', array(
'type'=>'checkbox',
'style' => 'float:left;',)
) ); ?>
<span>required</span>
</div>
答案 0 :(得分:0)
/ 请将输入更改为任何唯一的选择器给任何ID或类按钮 /
$("input").click(function(){
var val = $(this).val();
$.ajax({url: "path_to_your_cake_php_file.php",
type: 'post', // performing a POST request
data : {
inputValue : val // will be accessible in $_POST['inputValue']
},
dataType: 'json',
success: function(result){
alert('value has been updated');
}});
})
答案 1 :(得分:0)
onclick函数应该有参数来指示提交了哪个答案。
function save(id)
{
var id = id;
switch(id)
{
case 1:
var buttonValue = "Yes";
break;
case 2:
var buttonValue = "No";
break;
}
var formData = new FormData();
formData.append("ButtonValue", buttonValue);
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
var array = xmlHttp.responseText;
//in array you store results echoed from php script
}
}
xmlHttp.open("POST", "file.php");
xmlHttp.send(formData);
}
file.php
<?php
$buttonValue = $_POST["ButtonValue"];
$con = mysqli_connect("host", "name", "pass", "db");
$res = mysqli_query($con, "Insert goes here");
mysqli_close($con);
?>
PS认为纯JavaScript比JQuery快近30倍
答案 2 :(得分:0)
使用jQuery和jquery-ajax。
HTML:
<td> <input type="button" onClick="save(this);" value="Yes">
<input type="button" onClick="save(this);" value="No">
</td>
JS:
function save(elem){
val = $(elem).val() == 'Yes' ? 1 : 0;
$.ajax({
type: "POST",
url: Your_php_file_path,
data: {button: val },
success: function(data){
//added
},
dataType: json
});
}
在服务器端,您可以按$_REQUEST['button']