Ive created a very basic HTML form which uses PHP to pass the values through to a SQL database. I'm attempting to do this through the jquery ajax method as I dont want the page to reload (this also seems like one of the simplest methods).
However it doesnt seem to work, the PHP page returns a 500 error code.
Right away need to warn you this is the first time ive tried this, so very probable its just a really stupid mistake with my syntax
HTML :
<form id ="form1">
<input type="text" name="Test">
<br><br>
<input type="number" name="TestNumber">
<br><br>
<input type="radio" name="sex" value="male" checked> Male
<br>
<input type="radio" name="sex" value="female"> Female
<br><br>
<input type="submit" value="Submit">
</form>
Javascript :
$(document).ready(function() {
console.log("jquery ready");
var frm = $('#form1');
frm.submit(function(ev) {
$.ajax({
type: "POST",
url: "form_validation.php",
data: frm.serialize(),
success: function(data) {
alert('ok');
}
});
ev.preventDefault();
});
});
PHP:
<html>
<head>
<title>Untitled</title>
</head>
<body>
<?php
$servername = "server";
$username = "user";
$password = "pass";
$dbname = "name";
$test = $_POST[Test];
$testNumber = $_POST[TestNumber];
$sex = $_POST[sex];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO test (Test, TestNumber, sex, date)
VALUES ('$test', '$testNumber', '$sex', now())";
$sqlback = "SELECT ID FROM `test` WHERE sex = \'Male\'";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully" + . $sqlback;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
</body>
</html>