Robin Dirksen Robin Dirksen - 5 months ago 23
Ajax Question

jquery ajax post selectbox array by name

I want to do an ajax request to update the status of an item, but for one or many selected item.

So how can I post all the selected checkbox items to process it on the handle page?

Here is some code I use., but it will only post one

item
to the process page.

<td>
<input type="checkbox" class="select-all" name="item[]" id="item[78]">
</td>
<td>
<input type="checkbox" class="select-all" name="item[]" id="item[182]">
</td>


And the javascript

$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': "{{ csrf_token() }}}"
}
});

var formData = {
item: $('input[name=item\\[\\]]').val(),
}

var type = "POST";
var my_url = "/posturl";

$.ajax({
type: type,
url: my_url,
data: formData,
success: function (data) {
console.log(formData);
console.log(data);
},
error: function (data) {
console.log('Error:', data);
}
});

Answer
  1. Assign the unique name to each checkbox
  2. Put all checkboxes in a form tag (all input fields in a single form).
  3. Use serialize() or serializeArray() for collecting data from form
  4. store data in var formData

Code:

<form id="form-name">
    <tr>
        <td>
            <input type="checkbox" name="item[1]">
        </td>
    </tr>
    <tr>
        <td>
            <input type="checkbox" name="item[32]">
        </td>
    </tr>
</form>

Javascript:

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': "{{ csrf_token() }}}"
    }
});

var formData = $('#form').serializeArray();

var type = "POST";
var my_url = "/posturl";

$.ajax({
    type: type,
    url: my_url,
    data: formData,
    success: function (data) {
        console.log(formData);
    },
    error: function (data) {
        console.log('Error:', data);
    }
});

This will post an array of items to the url.image upload