I am struggling with inserting data into my database. The thing is that if I do "form action = "adduser.php" method = "post" then it works. However, it loads a new page and I don’t want that.
function addUser() {
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) {
}
};
xmlhttp.open("POST", "adduser.php");
var formData = new FormData(document.getElementById("new_person"));
xmlhttp.send(formData);
}
<form onsubmit="addUser()">
Name: <input id = "new_name" type="text" name = "new_name">
<button type="submit"> Submit </button>
</form>
<?php
$conn = pg_connect(******);
$name = pg_escape_string($_POST['name']);
$query = "INSERT INTO highscores (name, score) VALUES ('$name', 200)";
$res = pg_query ($conn, $query);
pg_close();
?>
<button type="submit"> Submit </button>
=><input type="button" value="submit" onclick="addUser()" />
also consider looking into jquery. api.jquery.com/jquery.ajax