bookthief
bookthief

Reputation: 2451

Passing checkbox values as JSON in Jquery

I have an input form which has three text fields and a checkbox input section where the user can select more than one value. I also have an ajax request which sends a POST request to an api. I have written a function to iterate over the form inputs and parse them to JSON, however, it has come to my attention that this wont work for checkbox values. Here is my function:

<script>
console.log(document);
var form = document.getElementById("myform");

form.onsubmit = function (e) {
    // stop the regular form submission
    e.preventDefault();

    // collect the form data while iterating over the inputs
    var info = {};
    for (var i = 0, ii = form.length; i < ii; ++i) {
        var input = form[i];
        if (input.name) {
            info[input.name] = input.value;
        }
        addPerson(info);
    }
}

function addPerson(info) {
    $.ajax({
        type: "POST",
        url: "http://example.com",
        data: JSON.stringify(info),
        contentType: "application/json; charset=utf-8",
        crossDomain: true,
        dataType: "json",

        success: function (data, status, jqXHR) {
            alert("success");
        },

        error: function (jqXHR, status) {
            // error handler
            console.log(jqXHR);
        }
    });
}
</script>

I've been trying to get the checkbox values into JSON using

$.each($('input[id="data[i].id"]:checked'), function() {
    var value = $(this).val();
    qualifications.push(value);
});

but I cant figure out how to add these values to the JSON that is being posted to the server, can anyone help?

Upvotes: 1

Views: 8176

Answers (2)

bookthief
bookthief

Reputation: 2451

Have tried .serialize() and I THINK it is working-

<script>

$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

$(function() {
    $('myform').submit(function() {
        $('#result').text(JSON.stringify($('myform').serializeObject()));
        return false;
    });
});


function addPerson(result){
  $.ajax({
         type: "POST",
         url: "http://example.com",
         data: JSON.stringify(result),
         contentType: "application/json; charset=utf-8",
         crossDomain: true,
         dataType: "json",

         success: function (data, status, jqXHR) {

             alert("success");
         },

         error: function (jqXHR, status) {
             // error handler
             console.log(jqXHR);

         }
      });
  }




</script>

If anyone has thoughts/ comments as to how effective the above is, or if there is a better way of doing it, I would like to hear them?

Upvotes: 4

karaxuna
karaxuna

Reputation: 26940

Try this:

var input = form[i];
if (input.name) {
    if(input.tagName.toLowerCase() === 'input' && 
       (input.type.toLowerCase() === 'checkbox' || input.type.toLowerCase() === 'radio') &&
       input.checked)
         info[input.name] = input.value;
    else
       info[input.name] = input.value;
}
addPerson(info);

EDIT:

I suggest using jQuery form.serialize() method as @Drixson Oseña mentioned.

Upvotes: 1

Related Questions