Ivan Nukli
Ivan Nukli

Reputation: 57

Stop page redirect after submitting the form with jQuery

I have a simple code, and I try to make a post without redirecting the page. So far my code looks like this:

$(function() {
    $('#btn').on('click', '.document', function(e) {
        e.preventDefault();
        $.ajax({
           
            type: 'post',
            url: '/save',
            data: {
                html: '<p>Sucess</p>',
                delay: 1
            },
            dataType: 'html',
           
            success: function(data) {
                console.log('success');
                $('.document').append(data);
            },
     
        });
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

  <form action="/save" method="post" autocomplete="off" id="theForm">
    
    <button id="btn" type="submit" name="send">
      Send
    </button> 
  </form>
  
  <span class="document"></span>

Can anybody try to help me with this? I don't know why my code doesn't work, I want to be able to POST without reloading and redirecting the page.

Upvotes: 0

Views: 529

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337700

You're attaching a delegated event handler to a span with no content, and the primary selector isn't a parent of that span.

The correct approach would be to attach a submit event handler to the form element instead.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form action="/save" method="post" autocomplete="off" id="theForm">
  <button id="btn" type="submit" name="send">Send</button>
</form>

<span class="document"></span>
jQuery($ => {
  $('#theForm').on('submit', e => {
    e.preventDefault();

    $.ajax({
      type: 'post',
      url: '/save',
      data: {
        html: '<p>Sucess</p>',
        delay: 1
      },
      dataType: 'html',
      success: function(data) {
        console.log('success');
        $('.document').append(data);
      }
    });
  });
});

Upvotes: 1

Related Questions