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>
This line is causing an error. Please remove the +.
echo "New record created successfully" + . $sqlback;
Also test your post vars:
$test = isset($_POST[Test]) ? $_POST[Test] : "";
Now $test always contains a value. If $_POST[Test] was undefined that would raise an error.
Your page is currently returning a 500 internal server error. PHP does that when an error is raised and error reporting is off.
Please turn error reporting on in your php.ini. It echo the error that is being raised inside the server side script, you can catch that error inside the network tab on your ajax request.
A tip as bonus:
You are loading a complete page (PHP code inside HTML body). You just want to return either success or failure when using an ajax call like this and not a complete HTML page. The common way these days is by using JSON.
Example based on your code, using PHP's json_encode to return JSON:
if ($conn->query($sql) === TRUE) {
echo json_encode(array("message" => "New record created successfully", "sql" => $sqlback));
} else {
echo json_encode(array("error" => $sql . "<br>" . $conn->error));
}
Now the data-type will be JSON. jQuery would probably guess that, but you can set the data-type : JSON in the ajax() options. data is automatically parsed into valid Javascript by jQuery using JSON.parse.
Now you can test in the success clause:
success: function(data) {
if (data.error)
{
alert(data.error);
}
else
{
alert(data.message + " " + data.sql);
}
}
Security advice:
$sql = "INSERT INTO test (Test, TestNumber, sex, date)
VALUES ('$test', '$testNumber', '$sex', now())";
This line is susceptible to SQL-injection. Use prepared statements in mysqli.
$sql = $conn->prepare("INSERT INTO test(Test, TestNumber, sex, date) VALUES (?, ?, ?, ?)");
$sql->bind_param("siss", $test, $testnumber, $sex, now()); //s = string, i = number
$sql->execute(); //execute the query;
$sql->close(); //close the statement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With