I'm trying to submit a form without refreshing the page, but event.preventDefault();
isn't working. Here's what I have thus far
$('#contactform').on('submit', function() {
event.preventDefault();
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
succss: function(response) {
console.log(response);
}
});
});
But the page still re-loads once the submit button has been pressed. Any suggestions?
Update: The code for the main form page is as follows;
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="<?php echo get_template_directory_uri();?>/ajax/main.js"></script>
<form action="<?php echo get_template_directory_uri(); ?>/ajax/contact.php" method="post" id="contactform">
<input type="text" name="fname" placeholder="Name" />
<input type="email" name="email" placeholder="Email" />
<textarea name="message" id="" cols="30" rows="10" placeholder="Your Message"></textarea>
<input type="submit" name="Submit" />
</form>
Try this
You need to put
event
into the function call:You need to pass the event to the function as the first parameter.
If that doesn't work, you may have an additional problem. You need to make sure the DOM is ready before binding anything to the form by wrapping your listener in a
.ready()
: