在复选框勾选中使用AJAX在MySQL数据库中插入数据

时间:2016-06-01 06:20:05

标签: javascript php mysql ajax onclick

在被困在这里之前,我看了一下问题here

的实施情况

我尝试实现代码,并希望在MySQL数据库内的复选框单击中插入数据。如果我本来应该在表单提交中插入数据,它可能已经完成但我必须通过在复选框勾选时打开/关闭它们来单独插入8位数据。

我尝试过,但不知道我到底哪里出错了。

以下是代码段:

PHP CODE insertIntoAbbaa.php:

<!DOCTYPE html>

<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <?php

    $updateCon = mysqli_connect("192.168.0.7", "uzer", "password", "remondb");
    if (!$updateCon) {
        die("not able to cconnect" . mysqli_error());
    }
    if(isset($_POST['firstOutputData'])){

        $firstData = mysqli_escape_string($updateCon, $_POST['firstOutputData']);

        if(!$firstData){
            echo "nopes !";
        }

        $updateValue = mysqli_query($updateCon, "INSERT INTO update_abbaa(rfu_id, upadate_index, update_value) values(1,'$firstData',1)");

        if(!$updateValue){
            echo "nopes !";
        }

        mysqli_close($dbget);
        echo "Saved !";
        }
    else{
        echo " nothing happened ! ";
    }
    ?>
</body>

下面是我打电话的onclick事件复选框勾选:

HTML onclick代码段:

<span class="toggle">
  <input type="checkbox" onclick="onOffFunction1()" id="onoff1">
  <label data-off="Off" data-on="On"></label>
</span> 

现在,我试图在javascript中调用上面提到的函数,如下所示:

function onOffFunction1() {
   var firstCb = document.getElementById("onoff1");

   if (firstCb.checked) {
       document.getElementById("firstBitData").innerHTML = "1";
       document.getElementById("firstBitData").style.backgroundColor = "green";
       var firstOutputData = "1";

 $.ajax({
       url: "insertIntoAbbaa.php",
       type : "POST",
       data : "firstOutputData"+firstOutputData,
       success: function(data)
         {
          alert("success !" + data);
         } 
     });

  }

输出显示我&#34;什么都没发生&#34;我用PHP脚本编写的消息

请放轻松我,我是初学者!

1 个答案:

答案 0 :(得分:0)

错误消息'Nothing occurred'是由于此检查引起的:

if(isset($_POST['firstOutputData']))

是假的。这意味着$_POST内的索引'firstOutputData'没有值。首先需要查找类似错误的是AJAX调用,如果正确传递参数,则不需要。

此:

data : "firstOutputData"+firstOutputData,

应该是:

data : {firstOutputData: firstOutputData}