jQuery - Illegal invocation

JqueryAjaxPost

Jquery Problem Overview


jQuery v1.7.2

I have this funcion that is giving me the following error while executing :

Uncaught TypeError: Illegal invocation

Here's the function :

$('form[name="twp-tool-distance-form"]').on('submit', function(e) {
	e.preventDefault();
	
	var from = $('form[name="twp-tool-distance-form"] input[name="from"]');
	var to = $('form[name="twp-tool-distance-form"] input[name="to"]');
	var unit = $('form[name="twp-tool-distance-form"] input[name="unit"]');
	var speed = game.unit.speed($(unit).val());
	
	if (!/^\d{3}\|\d{3}$/.test($(from).val()))
	{
		$(from).css('border-color', 'red');
		return false;
	}
	
	if (!/^\d{3}\|\d{3}$/.test($(to).val()))
	{
		$(to).css('border-color', 'red');
		return false;
	}
	
	var data = {
		from : from,
		to : to,
		speed : speed
	};
	
	$.ajax({
		url : base_url+'index.php',
		type: 'POST',
		dataType: 'json',
		data: data,
		cache : false
	}).done(function(response) {
		alert(response);
	});
	
	return false;
});

If I remove data from ajax call, it works .. any suggestions?

Thanks!

Jquery Solutions


Solution 1 - Jquery

Try to set processData: false in ajax settings like this

$.ajax({
    url : base_url+'index.php',
    type: 'POST',
    dataType: 'json',
    data: data,
    cache : false,
    processData: false
}).done(function(response) {
    alert(response);
});

Solution 2 - Jquery

I think you need to have strings as the data values. It's likely something internally within jQuery that isn't encoding/serializing correctly the To & From Objects.

Try:

var data = {
    from : from.val(),
    to : to.val(),
    speed : speed
};

Notice also on the lines:

$(from).css(...
$(to).css(

You don't need the jQuery wrapper as To & From are already jQuery objects.

Solution 3 - Jquery

Just for the record it can also happen if you try to use undeclared variable in data like

var layout = {};
$.ajax({
  ...
  data: {
    layout: laoyut // notice misspelled variable name
  },
  ...
});

Solution 4 - Jquery

If you want to submit a form using Javascript FormData API with uploading files you need to set below two options:

processData: false,
contentType: false

You can try as follows:

//Ajax Form Submission
$(document).on("click", ".afs", function (e) {
    e.preventDefault();
    e.stopPropagation();
    var thisBtn = $(this);
    var thisForm = thisBtn.closest("form");
    var formData = new FormData(thisForm[0]);
    //var formData = thisForm.serializeArray();

    $.ajax({
        type: "POST",
        url: "<?=base_url();?>assignment/createAssignment",
        data: formData,
        processData: false,
        contentType: false,
        success:function(data){
            if(data=='yes')
            {
                alert('Success! Record inserted successfully');
            }
            else if(data=='no')
            {
                alert('Error! Record not inserted successfully')
            }
            else
            {
                alert('Error! Try again');
            }
        }
    });
});

Solution 5 - Jquery

In my case, I just changed

Note: This is in case of Django, so I added csrftoken. In your case, you may not need it.

> Added contentType: false, processData: false > > Commented out "Content-Type": "application/json"

$.ajax({
	url: location.pathname, 
	type: "POST",
	crossDomain: true,
	dataType: "json",
	headers: {
		"X-CSRFToken": csrftoken,
		"Content-Type": "application/json"
	},
	data:formData,
	success: (response, textStatus, jQxhr) => {

	},
	error: (jQxhr, textStatus, errorThrown) => {

	}
})

to

$.ajax({
	url: location.pathname, 
	type: "POST",
	crossDomain: true,
	dataType: "json",
	contentType: false,
	processData: false,
	headers: {
		"X-CSRFToken": csrftoken
		// "Content-Type": "application/json",
	},
	data:formData,
	success: (response, textStatus, jQxhr) => {

	},
	error: (jQxhr, textStatus, errorThrown) => {

	}
})

and it worked.

Solution 6 - Jquery

In My case I have't define all variables which I am passing to data in ajax.

var page = 1;

$.ajax({
	url: 'your_url',
	type: "post",
	data: { 'page' : page, 'search_candidate' : search_candidate }
	success: function(result){
		alert('function called');
	}
)}

I have just defined variable var search_candidate = "candidate name"; and its working.

var page = 1;
var search_candidate = "candidate name"; // defined
$.ajax({
	url: 'your_url',
	type: "post",
	data: { 'page' : page, 'search_candidate' : search_candidate }
	success: function(result){
		alert('function called');
	}
)}

Solution 7 - Jquery

My problem was unrelated to processData. It was because I sent a function that cannot be called later with apply because it did not have enough arguments. Specifically I shouldn't have used alert as the error callback.

$.ajax({
    url: csvApi,
    success: parseCsvs,
    dataType: "json",
    timeout: 5000,
    processData: false,
    error: alert
});

See this answer for more information on why that can be a problem: https://stackoverflow.com/questions/10743596/why-are-certain-function-calls-termed-illegal-invocations-in-javascript

The way I was able to discover this was by adding a console.log(list[ firingIndex ]) to jQuery so I could track what it was firing.

This was the fix:

function myError(jqx, textStatus, errStr) {
    alert(errStr);
}

$.ajax({
    url: csvApi,
    success: parseCsvs,
    dataType: "json",
    timeout: 5000,
    error: myError // Note that passing `alert` instead can cause a "jquery.js:3189 Uncaught TypeError: Illegal invocation" sometimes
});

Solution 8 - Jquery

In my case (using webpack 4) within an anonymous function, that I was using as a callback.

I had to use window.$.ajax() instead of $.ajax() despite having:

import $ from 'jquery';
window.$ = window.jQuery = $;

Solution 9 - Jquery

Also this is a cause too: If you built a jQuery collection (via .map() or something similar) then you shouldn't use this collection in .ajax()'s data. Because it's still a jQuery object, not plain JavaScript Array. You should use .get() at the and to get plain js array and should use it on the data setting on .ajax().

Solution 10 - Jquery

Working for me. processData: false, contentType: false, is required for working.

 var formData = new FormData($('#author_post')[0]);
 formData.append('t','author-add');
 $.ajax({
		type: 'POST',
		url: 'url-here',
		cache: false,
        processData: false,
        contentType: false,
		data:formData,
		success: function(response) {
           //success code
        }
 });

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionyodaView Question on Stackoverflow
Solution 1 - JqueryJustoView Answer on Stackoverflow
Solution 2 - JqueryLessQuesarView Answer on Stackoverflow
Solution 3 - JqueryIvan IvanicView Answer on Stackoverflow
Solution 4 - JqueryBablu AhmedView Answer on Stackoverflow
Solution 5 - JqueryhygullView Answer on Stackoverflow
Solution 6 - JqueryRajesh KharatmolView Answer on Stackoverflow
Solution 7 - JqueryubershmekelView Answer on Stackoverflow
Solution 8 - JqueryzanderwarView Answer on Stackoverflow
Solution 9 - JqueryBurak TARHANLIView Answer on Stackoverflow
Solution 10 - JqueryRana NadeemView Answer on Stackoverflow