JavaScriptを使用してページを更新せずにデータベースに値を挿入する単純なコードがあります。問題は、メソッドで「onchange」属性を使用して関数を呼び出すと、コードが正常に機能し、値が挿入されることですが、「onchange」フォームを削除し、ボタンの「onclick」属性を使用して同じメソッドを呼び出すと、一度動作し、その後、動作を停止します。
私のcomment.htmlファイルのコードは
<html>
<head>
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
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","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form method="GET">
<input type="text" name="q">
<button method="GET" onclick="showUser(q.value)">Submit</button>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here.</b></div>
</body>
</html>
私のgetuser.phpファイルのコードは次のとおりです。
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','root','','login');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql2= "INSERT INTO `users` ( `FirstName`) VALUES( '{$_GET['q']}') ";
$result = mysqli_query($con,$sql2);
while($row = $result)
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>