user2585051
user2585051

Reputation: 23

event.preventDefault(); not working

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>

Upvotes: 1

Views: 10106

Answers (3)

Ravi Yadav
Ravi Yadav

Reputation: 11

Try this

$('#contactform').submit(function(event) {
event.preventDefault();
 });

Upvotes: 1

nullability
nullability

Reputation: 10677

You need to pass the event to the function as the first parameter.

$('#contactform').on('submit', function(event) {

    event.preventDefault();

...

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():

$(document).ready(function() {
    $('#contactform').on('submit', function(event) {
        event.preventDefault();
        ...

Upvotes: 12

Naftali
Naftali

Reputation: 146302

You need to put event into the function call:

$('#contactform').on('submit', function(event) { ...

Upvotes: 4

Related Questions