Tuesday, May 23, 2017

Ajax Reponse Laravel to object

I created an ajax request to display results from my table eloquent query who depends one a select box "poule".

Everything is working but when I run the ajax request by selecting a poule_id from the select box I need to display the json result. I would like to display the result as my foreach loop in the table ($equipes as $equipe) because as you can see I display value from models in relation.

Actually with this way I can only display equipe_id but i would like to display the object to access to the other models in relation and display the result as my foreach in the table like :

@foreach($equipes as $equipe)
    <tr>
        <td>
            <a href="{!! route('club.show', $equipe->equipe->structure->id) !!}"></a>
        </td>
        <td>
            <a href="{!! route('equipe.show', $equipe->equipe->id) !!}"></a>
        </td>
        <td>{!! Form::text('nb_bonus') !!}</td>
    </tr>
@endforeach

Hope someone understood what I want to do. thanks a lot in advance friends

My select filter search :

<select id="poule">
  @foreach($select_poules as $select_poule)
      <option value=""></option>
  @endforeach
</select>

My table :

<table id="equipes" class="table table-striped">
    <thead>
        <tr>
            <th>Club</th>
            <th>Nom de l'équipe</th>
            <th>Bonus(+/-)</th>
        </tr>
    </thead>
    <tbody>
        @foreach($equipes as $equipe)
        <tr>
            <td>
                <a href="{!! route('club.show', $equipe->equipe->structure->id) !!}"></a>
            </td>
            <td>
                <a href="{!! route('equipe.show', $equipe->equipe->id) !!}"></a>
            </td>
            <td>{!! Form::text('nb_bonus') !!}</td>
        </tr>
        @endforeach
    </tbody>
</table>

My script :

<script>
    $(document).on('change', '#poule', function() {

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

        $.ajax({
            type: 'GET',
            dataType: "json",
            url : '/licences/public/search/equipes',
            data : {
                poule_id : $('#poule').val()
            },
            success:function(data){

                $('#equipes').empty();
                for (var i = 0; i < data.equipes.length; i++) {
                    $('#equipes').append('<tr><td>'+data.equipes[i].equipe_id+'</td></‌​tr>')
                }

            },
            timeout:10000
        });

    });
</script>



via Mathieu Mourareau

Advertisement