为什么不使用Ajax在数据库中插入这些值

时间:2015-02-21 06:47:50

标签: php jquery ajax mysqli

我使用tutorialspoint来指导我将输入文本中的值插入到db中,但遗憾的是,它不会插入到数据库中。这是AJAX的正确实现吗?

这是我的index.php

<html>
<body>

<script language="javascript" type="text/javascript">
<!-- 
//Browser Support Code
function ajaxFunction(){
   var ajaxRequest;  // The variable that makes Ajax possible!
   try{

      // Opera 8.0+, Firefox, Safari
      ajaxRequest = new XMLHttpRequest();
   }catch (e){

      // Internet Explorer Browsers
      try{
         ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
      }catch (e) {

         try{
            ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
         }catch (e){

            // Something went wrong
            alert("Your browser broke!");
            return false;
         }
      }
   }

   // Create a function that will receive data
   // sent from the server and will update
   // div section in the same page.
   ajaxRequest.onreadystatechange = function(){

      if(ajaxRequest.readyState == 4){
         var ajaxDisplay = document.getElementById('ajaxDiv');
         ajaxDisplay.innerHTML = ajaxRequest.responseText;
      }
   }


   // Now get the value from user and pass it to
   // server script.
   var fname = document.getElementById('fname').value;
   var lname = document.getElementById('lname').value;
   var gen = document.getElementById('gen').value;
  // var queryString = "?age=" + age ;

    queryString +=  "&fname=" + fname + "&lname=" + lname+ "&gen=" + gen;
   ajaxRequest.open("GET", "ajax.php" + queryString, true);
   ajaxRequest.send(null); 
}
//-->
</script>

<form name='myForm'>

   First Name: <input type='text' id='fname' /> <br />
   Last Name: <input type='text' id='lname' /> <br />
   Sex: 
   <select id='gen'>
      <option value="m">m</option>
      <option value="f">f</option>
   </select>
   <input type='button' onclick='ajaxFunction()' value='Query MySQL'/>

</form>
<div id='ajaxDiv'>Your result will display here</div>
</body>
</html>

ajax.php

<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "my_db";


$con =  new mysqli($dbhost, $dbuser, $dbpass,$dbname);


$query="INSERT INTO table1 (fname, lname, gender)
VALUES
('$_GET[fname]','$_GET[lname]','$_GET[gen]')";

$qry_result = $con->query($query);


?>

3 个答案:

答案 0 :(得分:1)

将您的代码更改为以下

var queryString;

queryString =  "fname=" + fname + "&lname=" + lname+ "&gen=" + gen;

ajaxRequest.open("GET", "ajax.php?" + queryString, true);

并确保ajax.php与index.php在同一个文件夹中

答案 1 :(得分:1)

在ajax.php中尝试:

$fname=$_GET['fname'];
$lname=$_GET['lname'];
$gen=$_GET['gen'];

$query="INSERT INTO table1 ('fname', 'lname', 'gender')
        VALUES('$fname','$lname','$gen')";

答案 2 :(得分:0)

声明Form method =“POST”

$query="INSERT INTO table1 (fname, lname, gender) VALUES
('".$_POST['fname']."','".$_POST['lname']."','".$_POST['gen']."')";