Laravel - AJAX POST Array of Choices from Checkbox

2019-07-29 05:59发布

问题:

I have an AJAX Post that I'm trying to fix, but with a multitude of checkboxes on the input, I'm getting stuck.

At the moment, say I've this:

<input type="checkbox" name="billToEmail[]" value="email1@email.com">email1@email.com
<input type="checkbox" name="billToEmail[]" value="email2@email.com">email2@email.com

And I've a button called "Send Notifications", which starts the following script:

<script>
$('.modal-footer').on('click', '.sendNotificationNow', function() {
    $.ajax({
        type:'POST',
        url: '/shipments/sendNotifications',
        data: {
            'billTo': $('.billToEmail:checked').val(),
            'shipTo': $('.shipToEmail:checked').val(),
            'shipFrom': $('.shipFromEmail:checked').val(),
            '_token': $('input[name=_token]').val(),
        },
        success: function(data) {
            $('.errorTitle').addClass('hidden');
            $('.errorContent').addClass('hidden');

            if ((data.errors)) {
                setTimeout(function () {
                    $('#sentNotifications').modal('show');
                    toastr.error('Validation error - Check your inputs!', 'Error Alert', {timeOut: 5000});
                }, 500);

                if (data.errors.title) {
                    $('.errorTitle').removeClass('hidden');
                    $('.errorTitle').text(data.errors.title);
                }

                if (data.errors.content) {
                    $('.errorContent').removeClass('hidden');
                    $('.errorContent').text(data.errors.content);
                }
            } else {
                toastr.success('Successfully Sent Notifications!', 'Success Alert', {timeOut: 5000});
                $('div.notificationssent').fadeOut();
                $('div.notificationssent').load(url, function() {
                    $('div.notificationssent').fadeIn();
                });
            }
        },
    });
});
</script>

Now, I'm sure my issues are popping up near the top, where I'm trying to "translate" the multiple values into the data variables. Should I be putting something besides .val()?

I've a few more fields like this that I need to work on with the multiple checkboxes but if I can get some help for the billToEmail alone, I'm sure I can fix the remainder.

回答1:

First, you don't need the [] sign. So, your checkbox html will look like this :

<input type="checkbox" name="billToEmail" value="email1@email.com">email1@email.com
<input type="checkbox" name="billToEmail" value="email2@email.com">email2@email.com

Second, you need to push selected value on checkbox into javascript array variable using foreach :

var billToEmail= [];

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

Third, you need to convert javascript array into string using JSON.stringify().

billToEmails= JSON.stringify(billToEmail);

Then after that, pass the billToEmails variable into your data in AJAX. So, it will look like this :

var dataString = "billTo="+billToEmails+"&shipTo="+$('.shipToEmail:checked').val()+"&shipFrom="+$('.shipFromEmail:checked').val()+"&_token="$('input[name=_token]').val();
$.ajax({
        type:'POST',
        url: '/shipments/sendNotifications',
        data: dataString,

In order to PHP can fetch the array, you need to decode the billToEmails string first using json_decode in your controller.

$variable = json_decode($request->billTo,true);


回答2:

Try this-

  billtoemail = $('input[name='billToEmail[]']:checked").map(function () {
      return this.value;
  }).get();

or

billtoemail= new Array();
$("input[name='billToEmail[]']").each(function(){
  billtoemail.push(this.value);
 });

Now send this variable billtoemail like other variable in your ajax. In your controller you can get all the values by a simple foreach($request->billTo as $billtoemail)