dimanche 5 août 2018

Array of Checkbox Value through AJAX to Laravel Controller

I have a table of data where each row has a checkbox with the following code:

<input type="checkbox" class="batchCheckbox" name="batch[]" value="(item id)">

I have an AJAX script which is called when I press a download button:

<script>
  $(document).ready(function(){
    $('#downloadTableData').click(function(){
      $.ajax({
        url: '/carrier/api/osd/download',
        data: {'batch[]': $('.batchCheckbox:checked').serialize(),
                '_token': $('input[name=_token]').val(),
              },
        type: 'POST',
        dataType: 'json',
        success: function (response) {
            console.log('Data downloaded.');
        }
    });
  });
 });
</script>

Now, as it stands this is what is sent via the request:

batch[]: batch%5B%5D=83&batch%5B%5D=66
_token: xxxxxxxxxxxxxxxxxxxxxxxGSSMWc

When in reality, it should be sending an array of values for batch: 83, 66

In my controller, I return a dd of $request->batch just to verify and this is what is returned:

array:1 [
  0 => "batch[]=83&batch[]=66"
]

Obviously, I require the numbers alone, is there a better way of formatting my AJAX to better request the batch[] data?

Thanks



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire