Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax running function inside my Class prototype?

function MyClass() {
    this.test = function () {
        return 'foo';
    }
}
MyClass.prototype.myMethod = function (data) {
    alert(data.name);
}
var newClass = new MyClass();
setTimeout(function () {
    $.ajax({
        url: '/echo/html/',
        data: newClass,
        success: function (data) {
            console.log('in success callback');
            console.log('received data: ' + data);
        }
    });
}, 3000);

Uncaught TypeError: Cannot read property 'name' of undefined

Why does ajax trigger newClass.myMethod? because of JSON parsing? how to avoid this error?

jsFiddle

like image 627
Rikard Avatar asked Feb 03 '26 07:02

Rikard


1 Answers

This happens because jQuery uses jQuery.param internally on the data, if you look at the source of jQuery.param it invokes all the functions and uses the result as data

So, I don't know what you want to do to get around it, but atleast you know what it is

jQuery.ajax part of source that is calling jQuery.param

// Convert data if not already a string
if (s.data && s.processData && typeof s.data !== "string") {
    s.data = jQuery.param(s.data, s.traditional);
}

jQuery.param part of source that calls function:

  var prefix, s = [],
        add = function (key, value) {
        // => If value is a function, invoke it and return its value
        value = jQuery.isFunction(value) ? value() : (value == null ? "" : value);
        s[s.length] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
    };

Update:

You can use processData: false to disable data processing, yet that means you will need to process your data manually like so

$.ajax({
    url: '/echo/html/',
    data: JSON.stringify(newClass), // pass the processed string
    processData: false,  // and add this 
    success: function (data) {
        console.log('in success callback');
        console.log('received data: ' + data);
    }
});
like image 90
iConnor Avatar answered Feb 04 '26 21:02

iConnor