How can I get my datatable via ajax request?

I try to load my datatable via Ajax:

base.html.twig:

 <button class="button">load table</button>

 <div class="result"></div>

  $('.button').on( 'click', function () {

  $.ajax({
    method:'POST',
    data: {
      "id": id,
    },
    url:'{{ path('table') }}',
    success : function (data) {
      $(".result").html(data.output);
    }
  });
 });

Controller:

  /**
  * @Route("/table", name="table", methods={"GET","POST"})
  */

  public function table(Request $request) {

    $id = $request->request->get('id');

     $file = 'files/file.json';

     $input = file_get_contents($file);
     $array = json_decode($input);

    foreach ($array as $key => $value) {
     if($key == "data"){
       $new = array_slice($value, 0, 10);
    }
   }

    $array->data = $new;

     $output = json_encode($array);

    $response = new JsonResponse(
      array(
     'message' => 'Success',
     'output' => $this->renderView('form/table.html.twig', array('output' => $output))), 200);

     return $response;
    }
  }

table.html.twig:

  My table:

   Here is my table:

  <table class="table">
  </table>


 <script type="text/javascript">
    var table = $('.table').DataTable({
       "serverSide": true,
       "ajax": '{{ output}}',

    });
</script>

file.json:

{
“draw”: 1,
“recordsTotal”: 57,
“recordsFiltered”: 57,
“data”: [
{
“DT_RowId”: “row_3”,
“DT_RowData”: {
“pkey”: 3
},
“first_name”: “Angelica”,
“last_name”: “Ramos”,
“position”: “System Architect”,
“office”: “London”,
“start_date”: “9th Oct 09”,
“salary”: “$2,875”
},
{
“DT_RowId”: “row_17”,
“DT_RowData”: {
“pkey”: 17
},
“first_name”: “Ashton”,
“last_name”: “Cox”,
“position”: “Technical Author”,
“office”: “San Francisco”,
“start_date”: “12th Jan 09”,
“salary”: “$4,800”
},

] }

When I click on my button, the text “Here is my table” is loaded. But I am expected now the table to be loaded as well. But there is nothing else to see on my page.

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *