I'm learning to create a submission form using AJAX and PHP. It is working, but only intermittently. Much of the time, the form does not update after hitting Submit. But when it does work (and shows my successful submission text), the page quickly refreshes again, and goes back to the form input page. What am I doing wrong?
Note: In case it's relevant, I also tried using the "POST" method, but I kept getting "405 Method not allowed" errors. I'm assuming that's to do with how my web server is setup, but I couldn't find any settings to allow (or deny) POST submissions. Just in case that has anything to do with the solution.
Here is my HTML page code:
<html>
<head>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
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 (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","refresh.php?q="+str.value,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form action="#" method="get" onsubmit="return showUser(this.name)">
<label>Name :</label>
<input id="name" name="name" placeholder="Name" type="text">
<input type="submit" value="Submit">
</form>
<br>
<div id="txtHint"><b>Table should show up here...</b></div>
</body>
</html>
And here is my "refresh.php" page code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
$q = strval($_GET['q']);
echo '<p>Hello World</p>';
echo $q;
echo "<p>Table shows up here!</p>";
?>
</body>
</html>