event.preventDefault(); not working

2019-08-09 02:59发布

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>

标签: jquery forms
3条回答
唯我独甜
2楼-- · 2019-08-09 03:35

Try this

$('#contactform').submit(function(event) {
event.preventDefault();
 });
查看更多
SAY GOODBYE
3楼-- · 2019-08-09 03:44

You need to put event into the function call:

$('#contactform').on('submit', function(event) { ...
查看更多
Luminary・发光体
4楼-- · 2019-08-09 03:45

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();
        ...
查看更多
登录 后发表回答