在onclick复选框上插入表行数据PHP, Ajax和MySQL


inserting table row data upon onclick checkbox PHP and Ajax and MySQL

我读过类似的主题,但还是写不完。

简而言之:您选中一个复选框,这将解锁一个调用函数的Ajax响应。该函数获取登录用户的ID。获得用户ID后,PHP脚本就可以运行了。

我已经重写了代码片段;我还没试过。我希望这能更接近。

我使用两个脚本,一个用于Ajax,另一个用于PHP。

Ajax:

    <html>
    <head>
    <script type="text/javascript">
    function getLoggedInUser()
    {
//IF THERE IS NOTHING CHECKED, THAT IS, STR == 0, THEN REMOVE WHATEVER WAS WRITTEN BEFORE
    if (str=="")
      {
      document.getElementById("txtHint").innerHTML="";
      return;
      } 

    // JUST CHECKING BROWSER COMPATIBILITY ISSUES FIRST
          if (window.XMLHttpRequest)
          {// code for IE7+, Firefox, Chrome, Opera, Safari
              xmlhttp=new XMLHttpRequest();
          }

          else
          {// code for IE6, IE5
              xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
          }

// IF THE SERVER HAS THE RESPONSE READY
          xmlhttp.onreadystatechange=function() 
          {
             if (xmlhttp.readyState==4 && xmlhttp.status==200)
            { 
     document.getElementById("txtHint").innerHTML=xmlhttp.responseText;

        }
      }
然后在选中了这个复选框后,它发送给GETLOGGED IN FN用户id,该函数将其转发给PHP脚本调用插入用户数据,这样就可以了。
xmlhttp.open("GET","insertUserData.php?$user="+str,true);

     xmlhttp.send();
  }

</script>
</head>

<body>

<?php $user = getUserId();?>
<form>
<input type="checkbox" name="asset" value="" onclick="getLoggedInUser($user)" /> I am potentially 
interested in this product or service<br />
<div id="txtHint"><b>Note:</b></div>

</form>
<br />
</body>
</html> 

= = = = = =这insertUserData.php PHP脚本 ===========

 <?php
 $user = $_GET['user'];

    // But now, as I indicated, we want the data corresponding to that ID

     $con = mysql_connect('localhost', 'peter', 'abc123');
        if (!$con)
          {
          die('Could not connect: ' . mysql_error());
          }
        mysql_select_db("ajax_demo", $con);

        $query = "SELECT name, country
                  FROM profiles
                  WHERE id = '". $user . "';
        $result = @mysql_query ($sql);
        $row = mysql_fetch_array($result, MYSQL_ASSOC);
        $name =  ($row['name']);
        $country =  ($row['country']);
        mysql_query("INSERT INTO Persons (name, country)
        VALUES ($name, $country)");
        echo 'Your interest has been saved';
        mysql_close($con);
        ?> 

提前感谢

至少:

$user = getUserId(); 
xmlhttp.open("GET","insertUserData.php?$user="true);

应改为:

<? $user = getUserId(); ?> 
xmlhttp.open("GET","insertUserData.php?user=$user", true);

这不是你问题的直接答案,但至少是一个起点,此外,确保通过在PHP文件的顶部添加以下代码来启用错误。

ini_set('display_errors', 1);
error_reporting(E_ALL);