I have a basic signup/ login page that submits the data to the SQL database with php. However, I would like the page not to redirect on submission with help of jQuery AJAX (either successful or not).
This is what I currently have and it is not working. It doesn't show any error messages.
HTML - signup.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Signup</title>
<meta charset="utf-8">
</head>
<body>
<form>
<table>
<tbody>
<tr>
<td>
<input type="text" name="first" placeholder="First Name" id="first">
</td>
</tr>
<tr>
<td>
<input type="text" name="last" placeholder="Last Name" id="last">
</td>
</tr>
<tr>
<td>
<input type="submit" value="Signup" id="signup">
</td>
</tr>
</tbody>
</table>
</form>
</body>
</html>
JavaScript - signup.js
function submit() {
$("form").submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'signup.php',
data: $('form').serialize(),
success: function() {
console.log("Signup was successful");
},
error: function() {
console.log("Signup was unsuccessful");
}
});
});
}
$(document).ready(function() {
submit();
});
PHP - signup.php
<?php
include_once "db_connect.php";
$post_FirstName = $_POST['first'];
$post_LastName = $_POST['last'];
$addData = "INSERT INTO details (firstname, lastname) VALUES ('$post_FirstName', '$post_LastName')";
if ($conn->query($addData) === TRUE) {
echo "Working";
} else {
echo "Not working";
}
?>
Here is the JSFiddle.
I hope you guys can help. Thanks in advance :)
If you are using ajax no need to use input type as submit
use button
.
$(document).ready(function() {
$("#signup").click(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'signup.php',
data: $('form').serialize()
success: function() {
console.log("Signup was successful");
}
error: function() {
console.log("Signup was unsuccessful");
}
});
});
Also change here
$post_FirstName = $_POST['first']; // name is `first` not `firstname`
You have some brakes and parentheses not properly closed
function submit() {
$("form").submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'signup.php',
data: $('form').serialize(),
success: function() {
console.log("Signup was successful");
},//here
error: function() {
console.log("Signup was unsuccessful");
}
});});//here
}
$(document).ready(function() {
submit();
});
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