0

Controller import() Import data from csv file and redirect with array of data

//import data from csv file
return redirect('school/student/import')->with('result', $result);

import.blade.php This is a modal form and imported data is shown to user.

 @if(Session::has('result'))
 @php
    $result = Session::get('result');
 @endphp
    <table class="table table-hover">
       <thead>
           ...
            <tr>
                @foreach($result as $datarow)
                   <tr>
                        <td>{{$datarow['student_no']}}</th>
                        ....
                   </tr>
                @endforeach
           </tbody>
        </table>
@endif
<button type="submit" class="btn btn-primary">Save changes</button>

@section('js')
    <script>
        @if(Session::has('result'))
            //$result = IS IT POSSIBLE TO ACCESS $result;
            
            $('#exampleModalCenter').modal('show');

            $("form#myForm").submit(function(event) {
                event.preventDefault();
                $('#exampleModalCenter').modal('hide');
                $.ajax({
                    type: "POST",
                    url: "savedata",
                    headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
                    data: **$result**,
                    success: function(data){
                        window.location = '{{ url("school/student") }}';
                    },
                });
            });
        @endif
    </script>
@stop

Once submit is clicked, I want to call Controller savedata() with $result data array. I tried with both form submit and ajax post but the issue is since $result is an array, it's difficult to pass. Also unable to access session values from JavaScript.

devnc
  • 70
  • 7

1 Answers1

0

Need to provide the route name

routes/web.php

Route::post('savedata', 'ExampleController@savedata')->name('example.savedata');

After naming the route, you need to provide the route name to the URL for ajax.

$("form#myForm").submit(function(event) {
    event.preventDefault();
    $('#exampleModalCenter').modal('hide');
    $.ajax({
        type: "POST",
        url: '{{route("example.savedata")}}',
        headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
        data: $result,
        success: function(data){
            window.location = '{{ url("school/student") }}';
        },
    });
});
Lizesh Shakya
  • 2,482
  • 2
  • 18
  • 42