0

I'm trying to retrieve a group of checkbox values, store into an array, and then use that array in my ajax data parameter.

I am getting an error back from my page stating that the data is not in the correct format. It needs to be an ienumerable.

Here is what I have so far:

    var years = new Array();
    $("#years input:checkbox[name=type]:checked").each(function() {
        if (checked == true) {
            years.push($(this).attr('name') + "=" + $(this).val());
        }
    });

    var ajaxData = years;

    $.ajax({
        type: "POST",
        url: url,
        dataType: "json",
        data: ajaxData
    });

How can I convert the array to a list-like format?

Thanks!

1
  • 1
    What is that variable checked doing? Also, shouldn't that statement always return true since you're only selecting "checked" checkboxes? Commented Apr 29, 2013 at 16:47

3 Answers 3

1

As tymeJV mentioned in the comment, you do not need to check if the checkbox is checked since you are already selecting those that are checked, so just do the following:

var years = new Array();
$("#years input:checkbox[name=type]:checked").each(function() {
   years.push($(this).attr('name') + '=' + $(this).val());
});

You should probably give your array a name:

var ajaxData = {
    years:years
};
$.ajax({
        type: "POST",
        url: url,
        dataType: "json",
        data: ajaxData
    });

Than from your server, you can grab the post variable named "years" containing the array.

Sign up to request clarification or add additional context in comments.

2 Comments

What does years:years do? I'm not quite how that statment works. Thanks
The jquery ajax data attribute is supposed to be a PlainObject or String, not an array. But your object can contain an array, so in this case the object contains an array called years
1

Try this:

var years = [];

$("#years input:checkbox[name=type]:checked").each(function () {
    years.push({
        name: $(this).attr('name'),
        val: $(this).val()
    });
});

var ajaxData = years;

Comments

1

Use JSON:

    var years = {
        theYears: []
    };

       var years = new Array();
        $("#years input:checkbox[name=type]:checked").each(function() {
            if (checked == true) {
                theYears.push({
                    "name" : $(this).attr("name"), 
                    "value" : + $(this).val()});
            }
        });


   var ajaxData = theYears;

    $.ajax({
        type: "POST",
        url: url,
        dataType: "json",
        data: ajaxData
    });

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.