1

当我选中复选框时,我需要一些 js/ajax/jquery 脚本将数据动态保存到数据库。目前的复选框或加载在记录旁边并根据是否选中更改数据库中的变量。但是我必须在选择一个将其保存到数据库后重新加载页面。我可以做其他所有事情,但了解如何为此实现 ajax,因此我不必每次都提交查询并刷新页面。任何帮助是极大的赞赏。

    <form name="form1aa" method="post" action="process.php?fn=<? echo $rows['first']; ?>&class=<?php echo $rows['class']; ?>&last=<?php echo $rows['last']; ?>
&model=<?php echo $rows['model']; ?>&cas=<?php echo $rows['cases']; ?>&upid=<?php echo $id; ?>&group=1" id="form1a" >

    <select name="type" onchange=" fill_damage (document.form1aa.type.selectedIndex); ">
    <option value="Hardware">Hardware</option>
    <option value="Software">Software</option>
    </select>
    <select name="damage">
    </select>
    <input type=text name="comment"  placeholder="Comments Box">
    <input type=text name="cost"  placeholder="Cost">
    <input type="submit" value="Save" name="Save">
    </form>

<?php

//Job Status
if(isset($_POST['checkbox'])){$checkbox = $_POST['checkbox'];
if(isset($_POST['activate'])?$activate = $_POST["activate"]:$deactivate = $_POST["deactivate"])
$id = "('" . implode( "','", $checkbox ) . "');" ;
$sql="UPDATE repairs SET status = '".(isset($activate)?'Completed':'In Progress')."' WHERE id=$id" ;
$result = mysql_query($sql) or die(mysql_error());
}
//End Job Status

//Payment Status
if(isset($_POST['paycheck'])){$paycheck = $_POST['paycheck'];
if(isset($_POST['paid'])?$paid = $_POST["paid"]:$unpaid = $_POST["unpaid"])
$id = "('" . implode( "','", $paycheck ) . "');" ;
$sql="UPDATE repairs SET paid = '".(isset($paid)?'Paid':'Unpaid')."' WHERE id=$id" ;
$result = mysql_query($sql) or die(mysql_error());
}
//End Payment Status

//Return Status
if(isset($_POST['retcheck'])){$retcheck = $_POST['retcheck'];
if(isset($_POST['ret'])?$ret = $_POST["ret"]:$unret = $_POST["unret"])
$id = "('" . implode( "','", $retcheck ) . "');" ;
$sql="UPDATE repairs SET ret = '".(isset($ret)?'Retuned':'In Office')."' WHERE id=$id" ;
$result = mysql_query($sql) or die(mysql_error());
}
//End Return Status
$sql="SELECT * FROM $tbl_name";
if(isset($_POST['all'])){
    $sql="SELECT * FROM $tbl_name";
}
if(isset($_POST['tpc'])){
    $sql="select * from $tbl_name WHERE class LIKE '1%'";
}
if(isset($_POST['drc'])){
    $sql="select * from $tbl_name WHERE class LIKE 'D%'";
}
if(isset($_POST['bsc'])){
    $sql="select * from $tbl_name WHERE class LIKE 'B%'";
}

$result=mysql_query($sql);

?>
<form  name="frmactive" method="post" action="">
                <input name="activate" type="submit" id="activate" value="Complete Job" />
                <input name="paid" type="submit" id="Payment" value="Payment Status" />
                <input name="ret" type="submit" id="ret" value="Returned 2 Student" />
                <br />

<a id="displayText" href="javascript:toggle();">Show Extra</a>
<div id="toggleText" style="display: none">
<br />
                <input name="unret" type="submit" id="unret" value="In Office" />
                <input name="unpaid" type="submit" id="unpaid" value="Not Paid" />
                <input name="deactivate" type="submit" id="deactivate" value="In Progress" /></div>

<table width="1000" border="0" cellpadding="3" cellspacing="1">
<thead>
<th width="67" align="center"><strong>Start Date</strong></th>
<th width="50" align="center"><strong>Cases</strong></th>
<th width="34" align="center"><strong>Type</strong></th>
<th width="120" align="center"><strong>Damage</strong></th>
<th width="31" align="center"><strong>Comment</strong></th>
<th width="31" align="center"><strong>Cost</strong></th>
<th width="90" align="center"><strong>Payment Status</strong></th>
<th width="100" align="center"><strong>Returned 2 Student</strong></th>
<th width="100" align="center"><strong>Job Status</strong></th>
</thead>

<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>

<td><? echo $rows['start']; ?></td>
<td><? echo $rows['cases']; ?></td>
<td><? echo $rows['type']; ?></td>
<td width="70"><? echo $rows['damage']; ?></td>
<td width="70"><? echo $rows['comment']; ?></td>
<td><? echo "$"; echo $rows['cost']; ?></td>

<!--Payment Display(Start)-->
<?php 
        if($rows['paid']=="Paid")
        {
                ?>
                    <td><input name="paycheck[]" type="checkbox" id="paycheck[]" value="<? echo $rows['id']; ?>">
                <? echo $rows['paid'];?>
                    </td>
                    <?
}

        if($rows['paid']=="Unpaid")
        {
              ?>
                    <td width="21"><input name="paycheck[]" type="checkbox" id="paycheck[]" value="<? echo $rows['id']; ?>">
                <? echo $rows['paid']; ?>
                    </td>
                    <?
}
if($rows['ret']==""){
    ?>
    <td width="50">No Data</td>
    <?
}
?>
4

4 回答 4

5

用 jQuery 来做,一个简单的例子可能是:

HTML:

<input type="checkbox" name="option1" value="Milk">
<input type="checkbox" name="option2" value="Sugar">
<input type="checkbox" name="option3" value="Chocolate">

JS:

$("input[type='checkbox']").on('click', function(){
   var checked = $(this).attr('checked');
   if(checked){
      var value = $(this).val();
      $.post('file.php', { value:value }, function(data){
          // data = 0 - means that there was an error
          // data = 1 - means that everything is ok
          if(data == 1){
             // Do something or do nothing :-)
             alert('Data was saved in db!');
          }
      });
   }
});

PHP:文件.php

<?php
if ($_POST && isset($_POST['value'])) {

    // db connection
    $link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
    if (!$link) {
       // error happened
       print(0);
    }
    mysql_select_db('mydb');

    // sanitize the value
    $value = mysql_real_escape_string($_POST['value']);

    // start the query
    $sql = "INSERT INTO table (value) VALUES ('$value')";

    // check if the query was executed
    if(mysql_query($sql, $link)){
       // everything is Ok, the data was inserted
       print(1);    
    } else {
       // error happened
       print(0);
    }
}
?>
于 2012-05-02T04:44:20.200 回答
1

简单的说...

$('input:checkbox').click( function() {
  clicked = $(this).attr('checked');
  if (clicked) {
    /* AJAX the server to tell them it was clicked. */ }
  else {
    /* AJAX the server to tell them it was unclicked. */ } } );
于 2012-05-02T04:33:37.150 回答
0

我可以让这更简单。首先,您需要添加一个复选框!

<form name="form1aa" method="post" action="process.php?fn=<? echo $rows['frist']; ?>&class=<?php echo $rows['class']; ?>&last=<?php echo $rows['last']; ?>
&model=<?php echo $rows['model']; ?>&cas=<?php echo $rows['cases']; ?>&upid=<?php echo $id; ?>&group=1" id="form1a" >

    <select name="type" onchange="fill_damage(document.form1aa.type.selectedIndex);">
    <option value="Hardware">Hardware</option>
    <option value="Software">Software</option>
    </select>
    <select name="damage">
    </select>
    <input type="text" name="comment"  placeholder="Comments Box">
    <input type="text" name="cost"  placeholder="Cost">
    <input type="checkbox" name="somecheck" onchange="if(this.checked)document.form1aa.submit()">Check this to Save.
    <input type="submit" value="Save" name="Save">
    </form>


<script type="javascript>
//another function that works for onchange="dosubmit(this)"
//IF you put it after the form.
function dosubmit(el) {
    if (el.checked) {
        document.form1aa.submit();
    }
}
</script>

尽可能去掉 onchange 事件中的空格。

于 2012-05-02T05:59:00.353 回答
0

如果您有动态复选框列表,并且希望将单击的复选框动态保存到数据库或插入未选中的复选框,请执行以下操作:

html/PHP

       <?php
        // $checklists are models that I am getting from db
        $checklists = CheckList::getCheckLists(3);
        echo '<ul>';
        foreach ($checklists as $checklist) {
            $isChecked = $checklist->getAnswer($requestID, $checklist->primaryKey);
            $checked = $isChecked ? "checked" : "";
            echo '<li>';
            echo "<input id='{$checklist->primaryKey}' 
            name='{$checklist->primaryKey}'  type='checkbox' {$checked} 
            value='{$isChecked}' data-request-id='{$requestID}'> 
            $checklist->check_list_text";
            echo '</li>';
        }
        echo '</ul>';
        ?>

jQuery

<script>
$("input[type='checkbox']").on('click', function(){
    var checkbox = $(this);
    var checked = checkbox.prop('checked');
    var checklistId = checkbox.attr("id");

    $.ajax({
        url:"<?= Url::to(['default/add-checklist-answer']) ?>",
        // I don't need to write the type here because I am using Yii Framework
        // type: 'post',
        data: {
            checklistId: checklistId,
            requestId: checkbox.data('request-id'),
            checked: checked
        },
        success: function(data) {
            //alert(data);
            console.log(data.firstMessage)
        },
        error: function(data) {
            // alert(data);
        }
    });

});

</script>

我希望它适用于 MVC 用户。

于 2021-04-25T13:10:29.367 回答