152

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?

13 Answers 13

186

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.

2
  • exactly what i was doing. Forgot to use .val() Commented Dec 7, 2017 at 15:02
  • I was passing the option, of a select html element in a variable. Did not notice it was not plain text but html. Commented May 31, 2019 at 12:16
83

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); 
    }
});
4
  • 7
    thanks man. u saved my day and my problem is solved with adding "processData: false, contentType: false, cache: false," in my ajax body. Thanks a lot.
    – CumaTekin
    Commented Mar 8, 2020 at 22:48
  • 15
    processData: false, contentType: false, cache: false, solved my problem.
    – hakki
    Commented Oct 23, 2020 at 15:53
  • this is the more proper answer. amazing saved my day big time. i was serializing and it was cool and smooth until files got larger.... Commented Sep 24, 2022 at 5:36
  • Thanks from me too, after 2 hours digging I got the fix from your solution by adding the processData: false in my ajax body. Commented Mar 12 at 18:20
56

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.

1
  • 1
    This is true. If I could have seen it before it would have pointed me to the actual error in my code. Thanks, I'll add a note in my answer. Commented Jun 17, 2012 at 12:43
14

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]
}];
6
  • 1
    it doesn't throw that error anymore but it seems that this data is not being passed to my $_GET array server-side (var_export($_GET) outputs array ( 'undefined' => 'undefined', )) Commented Jun 17, 2012 at 12:07
  • @nadirs: Try defining method type in your $.ajax handler: type:'get',
    – Sarfraz
    Commented Jun 17, 2012 at 12:09
  • @Sarfraz the result is the same. Server-side, data keys should be found in GET array, right? Or maybe they're sent via another request method anyway? Commented Jun 17, 2012 at 12:14
  • @nadirs: Something like this works data: {foo:'myfoo', bar:'mybar'}, there might be some other problem I think.
    – Sarfraz
    Commented Jun 17, 2012 at 12:19
  • @Sarfraz I'm an idiot, I was sending an HTML object e[e.selectedIndex] while I should have passed its value e[e.selectedIndex].value. After fixing this flaw, object notation works fine. Commented Jun 17, 2012 at 12:32
11

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

2
  • This actually works, I'm assuming for modern browsers only though
    – barnacle.m
    Commented Jun 22, 2017 at 14:22
  • Looks like this did the trick. .. Have no idea why. .. Also has no idea why it stopped to work at first place - everything was ok before!
    – Ingus
    Commented Apr 9, 2021 at 13:51
11

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.

8

I was getting the same problem and I could correct it as follows.

var formData = new FormData(document.getElementById('form_id'));
                                
$.ajax({
  type: 'POST',
  url: '/Settings/de_acc',
  data: formData,
  cache: false,
  contentType: false,
  processData: false,
  success: function(res){
    console.log(res);
  }
})
1
  • well done machan
    – Desper
    Commented Jan 17 at 7:08
3

My illegal invocation error on $.getJSON was caused by passing undefined as one of the values for the data object. Fixing that solved the error.

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;
        }
    });
}
2
  • 4
    A good answer is more than just a code snippet. It should explain why this answers the initial question and provide links to the relevant documentation, if available.
    – JSTL
    Commented Aug 23, 2018 at 17:35
  • Without the two fields contentType and processData, the error will keep showing. I added the two fields and it worked for me. I think op was trying to indicate the two important fields. Commented Mar 27, 2020 at 14:08
0

Ajax does no allow for a JSON object as the data. Using JSON.stringify() might solve the issue. Something like this:

function do_ajax(elem, mydata, filename)
{
    $.ajax({
        url: filename,
        context: elem,
        data: JSON.stringify(mydata), //Here's the change
        datatype: "html",
        success: function (data, textStatus, xhr) {
            elem.innerHTML = data;
        }
    });
}
0

JQUERY CHANGES : on your JQUERY you need to put this to make your data send as an array

JSON.stringify(yourArr);

LARAVEL CHANGES : then you need to do this on your LARAVEL controller to get the array correctly (just like a php array) :

json_decode($request->theArray);
-1

Try This:

            $.ajax({
                    url:"",
                    type: "POST",
                    data: new FormData($('#uploadDatabaseForm')[0]),
                    contentType:false,
                    cache: false,
                    processData:false,
                    success:function (msg) {}
                  });
-1
$.ajax({
                    url:"",
                    type: "POST",
                    data: new FormData($('#uploadDatabaseForm')[0]),
                    contentType:false,
                    cache: false,
                    processData:false,
                    success:function (msg) {}
                  });
1
  • 7
    Answers are more helpful if you include an explanation.
    – Jon B
    Commented Feb 22, 2018 at 16:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.