Thursday, 8 August 2013

Ajax prevent form action and post form data

Ajax prevent form action and post form data

I have been searching through examples for days trying to troubleshoot my
simple email signup form. I am trying to just submit an email to a
database without leaving or reloading the current page. I am able to
insert new data to my database, but not through my Ajax function. I am
starting to think that my Ajax function is not being called, because even
with the event.preventDefault(); function, my page is redirected to the
.php file. I have listed my script below which currently resides in the
<head></head> section of my HTML.
<script type="text/javascript">
$(document).ready(Function() {
$("#submitbtn").click(function(event) {
event.preventDefault();
var form = $(this),
emailcode = form.serialize(),
formUrl = form.attr('action'),
formMethod = form.attr('method');
/* responseMsg = $('#signup-response') */
if ( formData.length===0 ) {
function(msg){
alert('Invalid Email');
}
return false;
} else {
//send data to server
$.ajax({
url: formUrl,
type: formMethod,
data: emailcode,
success:function(data){
alert('Email Saved');
}
return false;
});
};
});
});
HTML
<form class="col-lg-5 form-group pull-right well" id="emailform"
action="collector.php" method="POST" style="padding-top:6px;">
<label for="email-input">Sign up to receive updates</label>
<input type="email" class="form-control" id="emailcode"
placeholder="Email" name="emaildata" autofocus></input>
<button type="submit" id="submitbtn" class="btn btn-success"
style="width:60%">Sign Up</button>
</form>
PHP
$emailcode = $_POST['emailcode'];
//Fetching from your database table.
$query = "INSERT INTO EmailCollector (EmailID, EmailCode, Active)
VALUES (NULL,'$emailcode', 0)";
$result = mysql_query($query);
mysql_close();
?>

No comments:

Post a Comment