简体   繁体   中英

jQuery, ajax multiple checkboxes into $_POST array

I'm trying to send $_POST data to another page to add sessions for a simple shopping cart.

I have a multiple forms within a PHP while loop each with multiple checkboxes, everything works apart from the checkboxes.

My question is how do I change this piece of code to change "item_extras" into an array?

if(this.checked) item_extras = $(this).val();

I have tried the following but, this just creates one line with all the values instead of another row within the array. If this is too confusing I could create a sample if it helps.

if(this.checked) item_extras += $(this).val();

$('form[id^="add_item_form"]').on('submit', function(){
    //alert("On Click Works");
    event.preventDefault();
    addItem($(this));
});

function addItem(ele) {
    //alert("I'm in the addItem Function");
    var item_id = ele.parent().parent().find("input[name=item_id]").val(); // get item id
    var item_name = ele.parent().parent().find("input[name=item_name]").val(); // get item name
    var item_options = ele.parent().parent().find('#options').val(); // get selected option
    var item_extras = "";

    $item_extras = ele.parent().parent().find('input[name^="extra"]'); // find all extras

    $item_extras.each(function() {
        if(this.checked) item_extras = $(this).val(); // how do i make this into an array???
    });

    alert("BEFORE AJAX");

    var dataString = 'item_id=' + item_id + '&item_name=' + item_name + '&item_options=' + item_options + '&item_extras[]=' + item_extras;

    alert(dataString);

    $.ajax({
        type: "POST",
        cache: false,
        url: "includes/cart.php",
        data: dataString,
        success: function () {
            $.ajax({
                url: 'includes/cart.php',
                success: function(data) {
                $('#cart').html(data);
                alert("AJAX SUCCESS");
                }
            });
        }
    });

    return false;
}

you can use serialize method. Form.serialize()

$( "form" ).on( "submit", function( event ) {
  event.preventDefault();
   var data = $(this).serialize();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM