deception
deception

Reputation: 25

jQuery push() returns error "undefined is not a function"

this code gives me an error when submitting he form "undefined is not a function in line 21" and I don't know why

$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

$("form[name=dForm]").submit(function(ev){
        ev.preventDefault();
        var data = $(this).serializeObject();
        data.push({name:"bonjour",value:bonjour});

 // do something here ...

})

or it must be an array not an object?

Upvotes: 2

Views: 2504

Answers (1)

Quentin
Quentin

Reputation: 943214

serializeObject returns o which is defined at the top of the function as {}.

push is a method of Array objects, not plain objects. It puts an item onto the end of an array.

Plain objects are unordered. There isn't an "end" to put the item onto, so it doesn't make sense for there to be a push method.

You, presumably, want to just create a new property with a given name and value.

data.push({name:"bonjour",value:bonjour});

should be

data.bonjour = bonjour;

Upvotes: 3

Related Questions