Latest

Wednesday, July 5, 2017

Laravel Cannot Export Data to Excel After Passing Variables in AJAX

Asked by: Resnef Immatong


I have a button Export to Excel for exporting the data projected in the pagination table. The Export button is working properly until I used AJAX to pass the variables to my controller using AJAX. I am not sure if the I am doing it right but my AJAX function is throwing the

    success: function(data) {
      $('#messModal').delay(1000).fadeOut(450);
      $('#messcontent').text('Data exported successfully');
      $('#messModal').modal('show');
      setTimeout(function(){$('#messModal').modal('hide');}, 1500);
    }

But the exporting is ignored after the modal message.

Here is my view, AJAX script and Controller. Please help me because I anot so familiar with AJAX.

View:

<a href="#" class="btn btn-success btn-md" style="border-radius: 0px;text-align: left;" onclick="u_excel();"><span class="glyphicon glyphicon-export"></span> Export to Excel</a>

AJAX script:

<script type="text/javascript">
  function u_excel()
  {
      $.ajax({
      url: '/getExportEnrollExcel',
      type: 'get',
      data: {
        '_token': $('input[name=_token]').val(),
        'area_code': $('select[name=s]').val(),
        'sy': $('select[name=sys]').val(),
        'semester': $('select[name=sem]').val(),
        'gender': $('select[name=sgender]').val()
        },
        success: function(data) {
          $('#messModal').delay(1000).fadeOut(450);
          $('#messcontent').text('Data exported successfully');
          $('#messModal').modal('show');
          setTimeout(function(){$('#messModal').modal('hide');}, 1500);
        }
    });
  }
</script>

and Controller:

public function getExportEnrollExcel(Request $request)
{
    Excel::create('Enrollment', function($excel) {

    $excel->sheet('Sheet 1', function($sheet) {

    $s = Input::get ( 's' );
    $sys = Input::get ( 'sys' );
    $sem = Input::get ( 'sem' );
    $sgender = Input::get ( 'sgender' );

        $enrollments=DB::table('enrollments')
        ->where('r_status','=','A')
        ->select("enrollments.*")
        ->get();
        foreach($enrollments as $enrollment) {
             $enroll_data[] = array(
                $enrollment->id,
                $enrollment->area_code,
                $enrollment->sy,
                $enrollment->semester,
                $enrollment->college,
                $enrollment->gender,
                $enrollment->tot_enroll
            );
             return response()->json($enrollment);
        }

    if ( !empty($enroll_data) )
    {
        $sheet->fromArray($enroll_data, null, 'A1', false, false);
        $headings = array('ID', 'Area Code','SY','Semester','College','Gender','Total');
        $sheet->prependRow(1, $headings);
    }else
    {
    return back()->with('info',' Sorry. No record to export.');    
    }
    });
})->export('xls');   
}


Source

No comments:

Post a Comment

Adbox