Reputation: 39
trying to store simple email data from website to mysql database, i've written the code however it is not working and i can't figure it out
<form class="subfield">
<input type="text" id="emailInput" name="email" type='email' placeholder="Enter Your Email here" required>
<input type="submit" id="inputSubmit" value="Subscribe">
<span id="st">Email Subscribed!</span>
</form>
<script type="text/javascript">
$(document).ready(function(){
$('#inputSubmit').click(function(){
var email = $('#emailInput').val();
$.ajax({
url:"form_process.php",
method:"POST",
data:{email:email},
success:function(data){
$("form").trigger("reset");
$('#st').fadeIn().html(data);
setTimeout(function(){
$('#st').fadeOut("Slow");
}, 2000);
}
});
});
});
</script>
<?php
//insert.php
$connect = mysqli_connect("localhost", "root", "", "testing");
if(isset($_POST["email"]))
{
$email = mysqli_real_escape_string($connect, $_POST["email"]);
$sql = "INSERT INTO `emails_list`(`email`) VALUES ('".$email."')";
if(mysqli_query($connect, $sql))
{
echo "email Subscribed";
}
}
?>
when submit button is clicked it redirects to the home page as it should and the url also shows the ?email= part but no data is stored on the database also seems no echo is sent from php
EDIT : i noticed the files are saved as index.php instead of index.html is it necessary to save as index.php
Upvotes: 0
Views: 67
Reputation: 101
$(document).ready(function(){
$('#inputSubmit').click(function(e){
e.preventdefault();
var email = $('#emailInput').val();
$.ajax({
url:"form_process.php",
method:"POST",
data:{email:email},
success:function(data){
$("form").trigger("reset");
$('#st').fadeIn().html(data);
setTimeout(function(){
$('#st').fadeOut("Slow");
}, 2000);
}
});
return false;
});
});
Upvotes: 0
Reputation: 3150
There are two thing you can do about:
Use a button instead of submit
this:
<input type="submit" id="inputSubmit" value="Subscribe">
to:
<input type="button" id="inputSubmit" value="Subscribe">
use preventDefault
Method
$(document).ready(function() {
$("#inputSubmit").click(function(e) {
e.preventDefault();
var email = $("#emailInput").val();
$.ajax({
url: "form_process.php",
method: "POST",
data: { email: email },
success: function(data) {
$("form").trigger("reset");
$("#st")
.fadeIn()
.html(data);
setTimeout(function() {
$("#st").fadeOut("Slow");
}, 2000);
}
});
});
});
Upvotes: 0
Reputation: 1734
possibly way to to prevent deafult browser action. Then call ajax request on submit.
$(document).ready(function(){
$('#inputSubmit').click(function(e){
e.preventdefault();
var email = $('#emailInput').val();
$.ajax({
url:"form_process.php",
method:"POST",
data:{email:email},
success:function(data){
$("form").trigger("reset");
$('#st').fadeIn().html(data);
setTimeout(function(){
$('#st').fadeOut("Slow");
}, 2000);
}
});
});
});
Upvotes: 2