1

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"
          } 
        
    }
2
  • your output is not clear , you want a json? so could you show the json you want with the keys name in json format Commented Mar 2, 2021 at 18:51
  • Have a look,by refresh the page Commented Mar 2, 2021 at 18:59

1 Answer 1

1

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()});
        }
    });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.