从Javascript中调用PHP脚本,将数据插入mysql数据库


calling a PHP script from Javascript to insert data to a mysql database

在我的html文件中有一个按钮,点击后我需要做两件事。(将数据插入数据库并重新加载页面)所以我在onclick事件中调用了一个javascript函数。

这是javascript文件中的函数:

function grandFinale()
{
     if (window.XMLHttpRequest)
     {// code for IE7+, Firefox, Chrome, Opera, Safari
         xmlhttp=new XMLHttpRequest();
  }
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
 {
  //document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
 }
}
xmlhttp.open("GET","insert.php?q=",true);
xmlhttp.send();
document.location.reload();
}

这是上面提到的insert.php文件

<?php
    $con = mysql_connect("localhost","uname","password");
if (!$con)
  {
   die('Could not connect: ' . mysql_error());
  }
mysql_select_db("SnakeDB", $con);
$sql="INSERT INTO masterTable (Name, Score) VALUES ('$_GET[name]','$_POST[txtScore1]')";
if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }
echo "1 record added";
mysql_close($con);
?>

这是HTML文件的一部分,其中包含我想更新到数据库的位置

<div class="modal-body">
 <p>You scored :: </p><p id="txtScore1"></p>
<input type="text" placeholder="Your Name" id="name"> </div>

问题是数据库没有更新!!只有重新加载才会发生。请给我一个解决方案

正如我所看到的,你没有把参数发送到脚本吗?!

将名称字段也附加到

xmlhttp.open("GET","insert.php?q=&name=" + encodeURIComponent(document.getElementById('name').value),true);

给定的代码没有经过测试,但应该以这种方式工作。

javascript中的错误是,您没有通过ajax向脚本发送任何值。

xmlhttp.open("GET","insert.php?q=",true);

q为空,未设置nametxtScore1

另外,在您的SQL语句中,您混淆了GET和POST值。

$sql="INSERT INTO主表(名称、分数)VALUES('$_GET[Name]','$_POST[txtScore1]')";

应写成:

   $sql="INSERT INTO masterTable (Name, Score) VALUES ('{$_GET['name']}','{$_GET['txtScore1']}')";

警告,在将GET或POST数据插入数据库之前,您应该始终检查这些数据!

你用jQuery标记了你的问题,但你没有使用它。你应该这样做。它会将您的javascript压缩为几行+不需要重新加载页面!

请参阅http://api.jquery.com/jQuery.getJSON/