Cancel redirect when sending a form

Asked

Viewed 348 times

-1

How can I make nothing change after sending ajax, the page stay in the same place and not be loaded again?

script

$(function() {
    $('.form-carro').submit(function(){
        $.ajax({
            url:'insert.php',
            type: 'post',
            data: $('.form-carro').serialize(),
            success: function (data) {
                $('.recebeDados').html (data);
            }          
        });
        return-false
    });
});

would just have to take the success?

  • Hello Pedro, your question is unclear. You have a syntax error `` return-false that you can simultaneously remove, and I imagine you need to $('.form-carro').submit(function(e){ e.preventDefault(); to prevent the form from reloading the page. That’s it?

  • 1

    Good, it worked, I just took the return-false and changed the $('.form-carro').submit(function(){ for $('.form-carro').submit(function(e){ e.preventDefault();, thank you very much

2 answers

3


To prevent a form from being submitted you have to stop the event submit. The way Javascript gives us is by calling e.preventDefault(); inside the event’s callback. So you have to do:

$(function() {
    $('.form-carro').submit(function(e){
        e.preventDefault();
        // ...etc 

Note also that you have a syntax error here: return-false. Actually that line that should be return false; nor is it necessary and you can remove.

0

As you are sending the data via Ajax, you would not need the Ubmit (neither the - - nor the event = $('. form-car'). Ubmit())...

You could modify your code as follows:

$(function() {
    $.ajax({
        url:'insert.php',
        type: 'post',
        data: $('.form-carro').serialize(),
        success: function (data) {
            $('.recebeDados').html (data);
        }          
    });
});

At most, if your code is on a button, you would have to receive an Event as a parameter of the onclick function and add a call to the preventDefault function early on:

event.preventDefault()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.