[html] JQuery: 'Uncaught TypeError: Illegal invocation' at ajax request - several elements

I have two select elements, A and B: when A's selected option changes, B's options must be updated accordingly. Each element in A implies many elements in B, it's a one-to-many relationship (A contains nations, B should contain cities located in the given nation).

The function do_ajax should run the asynchronous request:

function do_ajax(elem, mydata, filename)
{
    $.ajax({
        url: filename,
        context: elem,
        data: mydata,
        datatype: "html",
        success: function (data, textStatus, xhr) {
            elem.innerHTML = data;
        }
    });
}

In order to update B's options I've added a function call in A's onChange event. Here is the function that runs when onChange event (of A) is triggered:

function my_onchange(e) // "e" is element "A"
{
    var sel_B = ... ; // get select element "B"

    // I skipped some code here
    // ...

    var data = {
        'mode': 'filter_city',
        'id_A': e[e.selectedIndex]
    };
    do_ajax(city_sel, data, 'ajax_handler.php');
}

}

I've read in JQuery docs that data can be an array (key value pairs). I get the error if I put:

var data = {
        'mode': 'filter_city',
        'id_A': e[e.selectedIndex]
};

Instead, I don't get that error if my data is a string:

var data = 'mode=filter_city&id_A=' + e[e.selectedIndex];

But I need the "array version" of the variable, in my server-side php code.

The Uncaught TypeError: Illegal invocation is located in the "jquery-1.7.2.min.js" file, which is all compressed, so I couldn't figure out what part of code raised the error.

Is there any setting I can change in my code so that it accepts data as an associative array?

This question is related to html ajax jquery

The answer is


Thanks to the talk with Sarfraz we could figure out the solution.

The problem was that I was passing an HTML element instead of its value, which is actually what I wanted to do (in fact in my php code I need that value as a foreign key for querying my cities table and filter correct entries).

So, instead of:

var data = {
        'mode': 'filter_city',
        'id_A': e[e.selectedIndex]
};

it should be:

var data = {
        'mode': 'filter_city',
        'id_A': e[e.selectedIndex].value
};

Note: check Jason Kulatunga's answer, it quotes JQuery doc to explain why passing an HTML element was causing troubles.


I've read in JQuery docs that data can be an array (key value pairs). I get the error if I put:

This is object not an array:

var data = {
        'mode': 'filter_city',
        'id_A': e[e.selectedIndex]
};

You probably want:

var data = [{
        'mode': 'filter_city',
        'id_A': e[e.selectedIndex]
}];

$.ajax({
                    url:"",
                    type: "POST",
                    data: new FormData($('#uploadDatabaseForm')[0]),
                    contentType:false,
                    cache: false,
                    processData:false,
                    success:function (msg) {}
                  });

Had the same issue recently, solved by adding traditional: true,


Please follow the procedure to get rid of this problem:

$.ajax({
   url: 'https://your-api-endpoint',
   type: 'post',
   data: new formData(this),
   processData: false,
   contentType: false,
   success: function(response) {
      console.log(response)
   }
})

You have to use processData: false and contentType: false, these two lines. Your problem will be solved.


From the jQuery docs for processData:

processData Boolean
Default: true
By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.

Source: http://api.jquery.com/jquery.ajax

Looks like you are going to have to use processData to send your data to the server, or modify your php script to support querystring encoded parameters.


Try This:

            $.ajax({
                    url:"",
                    type: "POST",
                    data: new FormData($('#uploadDatabaseForm')[0]),
                    contentType:false,
                    cache: false,
                    processData:false,
                    success:function (msg) {}
                  });

I was getting this error while posting a FormData object because I was not setting up the ajax call correctly. Setup below fixed my issue.

var myformData = new FormData();        
myformData.append('leadid', $("#leadid").val());
myformData.append('date', $(this).val());
myformData.append('time', $(e.target).prev().val());

$.ajax({
    method: 'post',
    processData: false,
    contentType: false,
    cache: false,
    data: myformData,
    enctype: 'multipart/form-data',
    url: 'include/ajax.php',
    success: function (response) {
        $("#subform").html(response).delay(4000).hide(1); 
    }
});

function do_ajax(elem, mydata, filename)
{
    $.ajax({
        url: filename,
        context: elem,
        data: mydata,
        **contentType: false,
        processData: false**
        datatype: "html",
        success: function (data, textStatus, xhr) {
            elem.innerHTML = data;
        }
    });
}

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?