Home » Jquery » jquery – multiple select field pass ajax data as string

jquery – multiple select field pass ajax data as string

Posted by: admin February 22, 2020 Leave a comment

Questions:

My problem is the quantity value pass as a string not as an array. like ["1,2"], however what I need is [1,2]

<div class="form-group col-md-4">
  <div class="form-group">
    <label for="title">Quantity:</label>
    <select name="quantity[]" id="quantity" class="form-control" multiple>
    </select>
  </div>
// get the quantity value:
if (res) {
  $("#quantity").empty();
  $.each(res, function(key, value) {
    $("#quantity").append('<option value="' + key + '">' + value + '</option>');
  });
} else {
  $("#quantity").empty();
}

// pass the quantity value:
var quantity = new Array(); //storing the selected values inside an array
$('#quantity :selected').each(function(i, selected) {
  quantity[i] = $(selected).val();
});

$.ajax({
  type: "POST",
  url: "{{route('localBook.store')}}?quantity[]=" + quantity,
  dataType: 'json',
  data: form_data,
  success: function(res) {}
});
How to&Answer:

I think this happens because you are passing the quantity-array as a url parameter instead of passing it in the http body (as intended in the post request). This is redundant if you want to perform a POST-request.

Edit your request, pass data through the data-field in your ajax request and everything will work fine. 🙂

$.ajax({
  type: "POST",
  url: "{{route('localBook.store')}}",
  dataType: 'json',
  data: {
    quantity: this.quantity
  },
  success: function(res) {}
});

Cheers,

Niklas