0

I have a simple HTML Form and in this form there is a section where the user can select one or more checkboxes. I have written a JS function that gets the value of every checked box and puts it into a string:

function getSupportedDevices() {
    var supportedDevices = "";
    $('.devices:checkbox:checked').each(function () {
        let sThisVal = $(this).val();
        supportedDevices += sThisVal + ";";
    });
    console.log(supportedDevices);

    return supportedDevices;
}

This function is called before the Ajax call and the result should be appended to the FormData so that I can use the string later on. Here is the code from where I try to add the list:

var $debForm = $('#formDeb');
if ($debForm.length > 0) {
    $debForm.on('submit', function (event) {
        event.preventDefault();

        if (!isSubmitting) {
            let $form = $(this);
            let targetUrl = $form.attr('action');
            let method = $form.attr('method');
            let $btnSubmit = getElement($form, '.js-btn-submit');

            var myFormData = new FormData(this);
            var supportedDevices = getSupportedDevices();
            myFormData.append("supportedDevices", supportedDevices);

            $.ajax({
                type: method,
                url: targetUrl,
                data: myFormData,
                async: true,
                beforeSend: function () { ...

Running this code throws an error:

Uncaught TypeError: Illegal invocation at add (jquery.js:8430) at buildParams (jquery.js:8417) at Function.jQuery.param (jquery.js:8450) at Function.ajax (jquery.js:9040) at HTMLFormElement. (submitdeb.js:45) at HTMLFormElement.dispatch (jquery.js:5206) at HTMLFormElement.elemData.handle (jquery.js:5014)

Line 45 is $.ajax. If I try data: new FormData(this).append("supportedDevices", getSupportedDevices()) as ajax parameter I get no error but the $_POST Array is empty.

What am I doing wrong that I get this error? The function to generate the string works on it's own and if I only send the FormData without anything appended, the $_POST Array is not empty.

1 Answer 1

1

Set processData:false to prevent $.ajax trying to serialize the FormData object using $.param() which it does by default when an object is passed to data.

The browser will handle the serializing internally

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.