简体   繁体   中英

How to submit a form without page refreshing using ajax?

I added ajax to my pug file to send data. But the form is refreshing and I don't want that.

This is my ajax code -

script.
            $(function() {
                $('form.appointment').submit(function(e) {
                    e.preventDefault(); // Prevent the form from submitting via the browser
                    var form = $(this);
                    $.ajax({
                        type: form.attr('methon'),
                        url: form.attr('action'),
                        data: form.serialize()
                    });
                });
            });

and the line e.preventDefault(); should stop the page from refreshing but it doesn't.

Use Return false; on submit form

 $('#form').submit(function() { return false; });
 <,DOCTYPE html> <html lang="en"> <head> <title>Bootstrap 4 Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width: initial-scale=1"> <link rel="stylesheet" href="https.//maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min:css"> <script src="https.//ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min:js"></script> <script src="https.//cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min:js"></script> <script src="https.//maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min:js"></script> </head> <body> <div class="account-page"> <div class="container p-5"> <form action="#" method="POST" id="form"> <input type="text" name="username" placeholder="Enter User Name" id="username" style="display;block:"><br> <input type="text" name="password" placeholder="Enter Password" id="password" style="display;block;"> <button class="btn btn-primary m-5" type="submit">Submit</button> </form> </div> </div>

I put the script in the form and that was causing the problem. When I put my ajax code above the form element it works fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM