Muhammad
Muhammad

Reputation: 634

Preventing refresh upon AJAX request

I have a form in my code, and I would simply like to display the fields from that form on my webpage, using AJAX. I tried e.preventDefault() and return false but none of these seem to be working.

I trigger the submit through a button click event.

My Jquery code:

$("body").on('click', '#save', function (e) {//button which triggers submit
    $('form').submit();
    e.preventDefault();
});

$('#form').on('submit', function(e){
    e.preventDefault();
    e.stopPropagation();
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    $.ajax({
        type: 'POST',
        url: '/results',
        data: $('#form').serializeArray(), 
        success: function (data) {
            //if no error from backend validation is thrown
            return false;
            $('#tabShow').html(data);      
        },
        error: function () {
            alert('error');
        }
    });

My form html is : <form class="form-horizontal" method="POST" action="/results" id="form">

In my web.php:

Route::post('/results', function() {
$m=Request::all();
var_dump($m);
});

The problem with this code is that it refreshes the current page that I am on. I have a save button, which should submit the form. I can't use a type submit because of my other functions.

Thank you for the help.

Upvotes: 1

Views: 273

Answers (2)

davcs86
davcs86

Reputation: 3935

Do the request in the Save button click event, eg.

HTML

<form id="contact-form" class="form-horizontal" action="/echo/html/" method="post">
    <!-- many fields -->
    <button id="save" class="btn btn-primary btn-lg">Submit</button>
</form>

JS

$("body").on('click', '#save', function (e) {//button which triggers 
    var contactForm = $('#contact-form');

    e.preventDefault();
    $.ajaxSetup({
        beforeSend: function(xhr) {
            xhr.setRequestHeader('X-CSRF-TOKEN', $('meta[name="csrf-token"]').attr('content'));
        }
    });

    // Send a POST AJAX request to the URL of form's action
    $.ajax({
      type: "POST",
      url: contactForm.attr('action'),
      data: contactForm.serialize()
    })
    .done(function(response) {
      console.log(response);
    })
    .fail(function(response) {
      console.log(response);
    });
});

Working demo

Upvotes: 2

Saurav
Saurav

Reputation: 363

Try using return false at the end of your script (also remove preventDefault() )

Upvotes: 0

Related Questions