Trewq Trewq - 4 years ago 385
Javascript Question

TypeError: undefined is not a function when serializing a form

I am new to js and am trying to serialize the values in a form to get it ready for submission into ajax.

In my browser, I get this error and I am not sure why:

$('#myform').serializeObject()
Uncaught TypeError: undefined is not a function


Here is the code I am running:

$.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;
};

$(document).ready(function () {
console.log("Hello there! How are you?");
mydata = JSON.stringify($('#myform').serializeObject());
console.log(mydata);
});


Here is a jsfiddle I created to make it easier. I thought the problem could be in
serializeObject
, but the debugger does not even get to that point.

UPDATE

Though I corrected this typo (which came up while I was creating the post), I get the same error. I tried this is firefox, and I got
TypeError: $(...).serializeObject is not a function
. Strangely, it works fine on jsfiddle.

Answer Source

My problem was that I had been calling my script before jquery was being loaded and therefore I was getting that error message. Duh. I am embarrassed, but wanted to post this just in case it can benefit someone.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download