使用AJAX对多个输入表单字段INTO mySQL db进行POST

时间:2012-09-20 20:48:32

标签: php mysql ajax

我正在尝试通过AJAX请求使用Java脚本将多个表单项从HTML提交到mySQL。我可以得到一个字段来更新而不是其他2.我已经注释掉了我认为有助于此的其他代码但是没有用。

 HTML part: 
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”
“http://www.w3.org/TR/html4/loose.dtd”>
<head>

<script type="text/javascript">

function insert()  {

      if (window.XMLHttpRequest) {
      xmlhttp = new XMLHttpRequest();
   } else {
       xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
   }
   xmlhttp.onreadystatechange = function(){
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    document.getElementById('message').innerHTML = xmlhttp.responseText;
  }
  }

 parameters = 'fname='+document.getElementById('fname').value;


   xmlhttp.open("POST", "update.php", true);
   xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
   xmlhttp.send(parameters);

} ;

 </script>

 </head>

 <body>

          First Name: <input class="work" type="text" id="fname" ><br>
          Middle Name: <input class="work" id="mname" type="text"><br>
          Last Name: <input class="work" id="lname" type="text"><br>
          <input type="button" value="Submit" onclick="insert();">

          <div id="message"></div>

  </body>
  </html>



 PHP part:
<?php
       //require 'connect.midasproject.php';
   $conn_error = 'could not connect.';

        $dbhost = "localhost";
        $dbname = "mastergolddb";
        $dbuser = "root";
        $dbpass = "";

 if (!@mysql_connect("$dbhost", "$dbuser", "$dbpass")||!@mysql_select_db ("$dbname")) {
   die($conn_error);
 } else {
   echo 'connected.';
   }

$fname = $_POST['fname'];
//$mname = $_POST['mname'] ;
//$lname = $_POST['lname'];

 if (!empty($fname))  {

$query = "INSERT INTO `customers` VALUES ('','$fname','joe','blow')";
    if  ($query_run = mysql_query($query)) {
       echo 'data inserted.' ;
    } else {
  echo 'Query failed.';
    }
   }

?>

1 个答案:

答案 0 :(得分:1)

您需要将所有3个值传递给ajax函数。你好像只是在这里经过fname parameters = 'fname='+document.getElementById('fname').value;