Sending two or more request by form with ajax

Asked

Viewed 1,001 times

1

Good afternoon guys, I want to know how I can send more than one form request to my Controller to do the relationship in the bank ?

I have a relationship N:M with User and Group, only when I give the Ubmit in the form it only considers a value of my form, but I need it to consider two or more values, basically I need the group ids that the users are related to in my controller, to be able to manipulate and make relationships. I did a search and I think I can do by ajax using Jquery, someone has some hint or knows how I can accomplish this feat ?

Thank you for your attention.

Form

<form action="{{ route('postGrupoUsuario') }}" method="post" class="centralizarNomes">
    {{ csrf_field() }}
    <div class="form-group">
        <label class="Usuarios_Lista">Usuarios </label>
        <select name="Usuario" class="form-control Selecionar_Usuario">  
            @foreach($listaUsuario as $usuario)
                <option value="{{ $usuario->Usuario_ID }}"> {{ $usuario->Usuario_Nome }}  </option>
            @endforeach
        </select>
    </div>
        <div class="table-responsive">
            <table class="table table-hover table-striped table-bordered">
                <thead>
                    <tr>
                        <th style="width: 65px;" class="text-center">ID</th>
                        <th>Nome do Grupo</th>
                        <th> Selecionar </th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($listaGrupo as $grupo)
                        <tr>
                            <td class="text-center"> {{$grupo->Grupo_ID }}</td>
                            <td> <span class="font-medium"> {{$grupo->Grupo_Nome }}</span></td>
                            <td> <input type="checkbox" name="Grupo" id="grupo" value="{{ $grupo->Grupo_ID }}"> </input> </td>
                        </tr> 
                    @endforeach
                </tbody>
            </table>
        </div>    
    </div>                                
    <div class="btn_Adc_Cancelar">                                                                              
        <a class="btn btn-inverse waves-effect waves-light"  href="{{ route('indexAdmin') }}" id="btn_cancelar">Cancelar</a>
        <button type="submit" class="btn btn-success waves-effect waves-light m-r-10" id="btn_cadastrar">Cadastrar</button>
    </div>
</form>  

Controller

public function ModelRelacaoPost (Request $request) //Faz o relacionamento
    {   
        $usuario_id = $request->get('Usuario'); //pega o id do usuário
        $grupo_id = $request->get('Grupo');//pego id do grupo

        $usuario = Usuario::find($usuario_id); //encontra com base na pesquisa
        $grupo = Grupo::find($grupo_id);//encontra com base na pesquisa

        $usuario->grupo()->attach($grupo); //faz o relacionamento

        return redirect()->route('grupoUsuario'); //redireciona
    }  

Currently I can make the User’s relationship with a Group but not for several groups. I’m using Laravel 5.5

1 answer

1


First you must put the token in the meta tags in the head to retrieve the information via ajax

<meta name="csrf-token" content="{{ csrf_token() }}">

then configure the global ajax with the token

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

now you need to set the submission via ajax to the form

$('form.centralizarNomes').on('submit',function(formEvent){
    formEvent.preventDefault(); //removendo ação submit;
             $.ajax({
            type: 'POST',
            url: window.getRoute('cadastranomes'), // ira ficar /api/form/cadastranomes
            dataType:'json',
            data: $(this).serialize() })
            .done(function(response) {
                //console.log(response);
                //resposta
            })
            .fail(function() { console.log("error"); })
            .always(function() { console.log("complete"); });
    })
return false; // para não redirecionar a página;

});

//recommend you create a header type function so you create a prefix route, so you can call the ajax url in a javascript file after you have to change the url of your route do not need to change all your javascript

window.getRoute = function (url) {
            var apiCall = '/api/form/'+url;
            return apiCall;
}

hope I’ve helped

Obs in the controller will need to set the response to json

in the controller you take your inputs by request in the same way will not change anything only the request via ajax

  • Bro I got to pass my full route or just the post route ?

  • vc can put the get route function or use it directly in the request & #Xa;replace url: window.getRoute('sign-in'), with url: '/api/form/sign-in,

Browser other questions tagged

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