0

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;
}
3
  • 1
    Try item_extras += '&item_extras[]=' + $(this).val(); Commented Apr 5, 2013 at 9:04
  • Are you using an array name in your form? Commented Apr 5, 2013 at 9:05
  • Thanks Victor that worked a treat :) Commented Apr 5, 2013 at 9:11

1 Answer 1

3

you can use serialize method. Form.serialize()

$( "form" ).on( "submit", function( event ) {
  event.preventDefault();
   var data = $(this).serialize();
});
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.