Send form without loading page via json

Asked

Viewed 165 times

0

I’m developing a website and I’m using Windows, and I need to send a form without updating the page, I’m using jquery but I don’t know much how someone can 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 the 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 to the wrong place it’s like a request GET inserir a descrição da imagem aqui

he of:

http://localhost/vitalento/public/jogar?_token=6H5lGaH436ibjo41uALi45Qct08aLocK3DObU9y6&desafiado=20

1 answer

1


You just need to prevent the return of the Submit function from being true. To do this, just follow the example below, adding a false Return 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;
    })
}

Browser other questions tagged

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