Home > other >  Who to submit a form without page refreshing using ajax?
Who to submit a form without page refreshing using ajax?

Time:11-28

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.

CodePudding user response:

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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.

  • Related