Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

gathuku's avatar

How to post data to laravel using Ajax

Hello , i have an array of data which am trying to pass to a laravel function in controller using ajax. Basically the array contains a list of selected checkbox and their values.

here is my javascript and ajax code

  <script type="text/javascript">

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

    document.getElementById('register_unit').addEventListener('click', function(){

    var selected = new Array();

    $(document).ready(function() {

      $("input:checkbox[name=check]:checked").each(function() {
           selected.push($(this).val());
      });

      console.log(postData)
      $.ajax({
      type: "POST",
      url: '/unit/register',
      data: selected,
      cache: false,
      success: function(data){
          alert(data);
      }
      });



    });
    });

    </script>

This is how am logging the data in my controller

  public function saveUnits(Request $request)
    {
      \Log::info($request->all());

    }

Upon logging , i receive an empty array in my log

[2019-03-14 12:23:27] local.INFO: array (
  'undefined' => NULL,
)  

Someone help!

0 likes
7 replies
sandersjj's avatar

Hi,

It seems your selected variable is empty. You should be able to post your form like this: var data = $('#myForm').serializeArray();

rawilk's avatar
rawilk
Best Answer
Level 47

Two things:

  1. For things like this, you don't need to use new Array(), instead use var selected = [];

  2. data should be an object, so try this instead: data: { selected: selected },

gathuku's avatar

@WILK_RANDALL - how will i be able to loop through the data and extract every value. bearing in mind the values may reduce or increase depending on user's choice.

[2019-03-14 16:08:52] local.INFO: array (
  'selected' => 
  array (
    0 => '1',
    1 => '2',
    2 => '3',
    3 => '4',
    4 => '5',
  ),
)  

rawilk's avatar

@gathuku In your controller, do something like this:

foreach ($request->get('selected') as $id) {
     // do something with $id
}

Also, FYI you can do a dd for an ajax request and see the results in the network tab of your browser's dev tools. In my opinion it's easier to do it that way than using Log

1 like

Please or to participate in this conversation.