jQuery - Illegal invocation

yoda picture yoda · Apr 26, 2012 · Viewed 316.9k times · Source

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!

Answer

LessQuesar picture LessQuesar · Apr 26, 2012

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.