Cancel redirection when submitting a form

-1

How can I make anything change after ajax is sent, the page stay in the same place and not load 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 you just have to remove success ?

    
asked by anonymous 18.10.2016 / 21:56

2 answers

1

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

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

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

    
18.10.2016 / 22:14
0

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

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 at the beginning of it a call to the preventDefault function:

event.preventDefault()
    
18.10.2016 / 22:38