Send form without loading page via json

0

I'm developing a website and I'm using laravel, and I need to send a form without updating the page, I'm using jquery, but I do not know much about it, can anyone help me?

html form

<form>
   {{csrf_field()}}
    <div class="user impar"><figure><img src="img/users/Profiles/Sem_FT.png"></figure><span class="nickname">1<span class="cartaoAmarelo cartaoAmarelo0"></span><button name="desafiado" type="hidden" value="20">DESAFIAR!</button> <p></p></span></div>
</form>

javascript to send to database

function desafio(){
    $('form').submit(function(e){
        e.preventDefault();
        var data=$(this).serializeArray();
        $.ajax({
         url: "desafio",
         type: "post",
         dataType: "json",
         data: data,   
       })
       .done(function() {
         alert( "success" );
       })
       .fail(function() {
         alert( "error" );
       })
       .always(function() {

       });
    })
}

It sends but reloads the page and sends it to the wrong place it does type if it was a request GET    

It gives:

http://localhost/vitalento/public/jogar?_token=6H5lGaH436ibjo41uALi45Qct08aLocK3DObU9y6&desafiado=20
    
asked by anonymous 16.07.2018 / 18:58

1 answer

1

You just need to prevent the return from the submit function from being true . To do this, just follow the example below, adding a return false to your function:

function desafio(){
    $('form').submit(function(e){
        e.preventDefault();
        var data=$(this).serializeArray();
        $.ajax({
         url: "desafio",
         type: "post",
         dataType: "json",
         data: data,   
       })
       .done(function() {
         alert( "success" );
       })
       .fail(function() {
         alert( "error" );
       })
       .always(function() {

       });
       return false;
    })
}
    
16.07.2018 / 20:54