Jquery: 'Uncaught TypeError: Illegal invocation' at ajax request - several elements
To quickly resolve the Uncaught TypeError: Illegal invocation
error during a jQuery AJAX call, make sure the data you pass is a plain object, not a DOM reference. Here's a clean-cut AJAX setup:
Remember: Simple key-value pairs for data
and always correctly use this
if needed.
Digging the error
Comprehending an "Illegal invocation" error in jQuery $.ajax
call generally roots back to a misfit data format. jQuery is all geared up for "associative arrays", easily consumable by your PHP server-side code. If you pass a jQuery or DOM object directly, jQuery can't transform it to "correct" associative array, leading to an error.
Handling complex data
Embrace FormData
For file uploads or when gathering disparate form fields, FormData
is your new best friend:
When to stringify
In cases where nested objects are involved, consider stringifying your data to avoid unwanted weirdness:
Array – a tricky friend
For PHP folks, keep the array structure in the chest of your pirate ship by using the square brackets [ ]
:
Circumventing common pitfalls
Non-processed data
If your data
is pretty and already in query string format or you need to dispatch a FormData
survey ship, set processData: false
(Oh look, FormData again!). It's like saying "Don't mess with my data
, jQuery!"
The object reference trap
Bookcase - a natural habitat of a book, not a book itself. Similarly, passing an object reference is not the same as passing the actual values:
Catching success & errors like a pro
Juggle server responses like a pro with jQuery callback functions:
Was this article helpful?