Sending multidimensional checkbox array via ajax in jQuery

I’m trying to post the multidimensional array values using checkbox to server side. But unfortunately cannot figure out the way to do it with checkbox.

What I trying to do is posting the ID, (NAME, VALUE) using ajax but yet only send one single array.

 <input type="hidden" id="addon_id" value="8"> //value is dynamic
 <input type="checkbox"  name='addon[]' value="1.99"  title="Item 1"> //value and title are dynamic
 <input type="checkbox"  name='addon[]' value="5.99"  title="Item 2"> 
 <input type="checkbox"  name='addon[]' value="3.99"  title="Item 3"> 

jQuery

var addon = [];

   $.each($("input[name='addon[]']"), function() {
        if ($(this).is(":checked")) {
            addon.push($(this).val());
        }
    });

    $.ajax({
      url: '<?php echo site_url('cart/add_to_cart'); ?>',
      type: 'POST',
      data: {
        addon_id: addon_id,
        addon: addon
      },
      dataType: "JSON",
      success: function(response) {

        //response

      }
    });

currently sending format

[addon] => Array
        (
            [0] => 1.99
            [1] => 5.00
            [2] => 3.89
        )

Array format trying to send

 Array
   (
       
    [8] =>  Array(
                     [0] =>  Array( 
                                    [name] => ITEM 1
                                    [price] => 1.99
                                  )

                     [1] =>  Array( 
                                    [name] => ITEM 2
                                    [price] => 5.99
                                  ) 
  
                     [2] =>  Array( 
                                    [name] => ITEM 3
                                    [price] => 3.99
                                  )     

                        
                    )
        

  )

JSON

"8":{
      "0":{ 
            "name":"ITEM 1",
           "price":"1.99"
          },
      "1":{ 
            "name":"ITEM 2",
            "price":"5.99"
          },
      "2":{ 
        "name":"ITEM 3",
        "price":"3.99"
          } 
        
    }

Answer

for the loop you have to include both values in an array:

  $.each($("input[name='addon[]']"), function() {
        if ($(this).is(":checked")) {
            addon.push({"name":$(this).attr("title"), "price":$(this).val()});
        }
    });

Leave a Reply

Your email address will not be published. Required fields are marked *