Sending two or more request by form with ajax or HTML

1

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

I have a N: M relationship with User and Group, but when I submit it on the form it only considers one value in my form, but I need it to consider two or more values, basically I need the ids of the groups that the users is related in my controller, to be able to manipulate and make the relationships. I have researched and think I can do for ajax using JQuery, does anyone have any tips or do you know how I can accomplish this feat?

Thanks 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 more   not for several groups.   I'm using Laravel 5.5

    
asked by anonymous 12.03.2018 / 17:48

1 answer

1

First you should 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 global ajax with token

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

Now you need to define the ajax submission for 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;

});

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

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

I hope to have helped

obs in the controller it will be necessary to configure the response as json

In the controller you get your inputs by the request in the same way it will not change anything just the request via ajax

    
13.03.2018 / 02:55