14

I'm using jQuery, and specifically this function

$("#postStatus").serializeObject();

It works absolutely fine in Chrome and Safari, but when I do it in Firefox it doesn't work. I used Firebug to see what error it was giving, and i'm getting this

$("#postStatus").serializeObject is not a function

Why doesn't this function work in Firefox?

UPDATE...

Oh yes, I completely forgot that it's not a core function. I remember that I searched a way to serialize a form and found this solution;

$.fn.serializeObject = function()
{
   var o = {};
   var a = this.serializeArray();
   $.each(a, function() {
       if (o[this.name]) {
           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;
};

I've managed to fix this issue by placing the function above at the top of the JS file. Thanks for your help guys.

Wasim
  • 4,953
  • 10
  • 52
  • 87

3 Answers3

9

AFAIK jQuery has no function defined as serializeObject in its core. Probably you are using a plugin, and that its problematic in Firefox only so its safe to assume that your script inclusion is in proper order, try wrapping up your code in the ready handler

$(function(e){
$("#postStatus").serializeObject();
});

or you can place the javascript at the bottom of the page.

DEMO

Rafay
  • 30,950
  • 5
  • 68
  • 101
  • Yes I completely forgot that it wasn't a core function, please read my edit above. – Wasim Jan 17 '12 at 20:33
  • Yes it works great thanks. I just placed the `serializeObject` function at the top of the JS file. – Wasim Jan 17 '12 at 20:53
1

You might also want to check this out https://github.com/citnvillareal/serializeObject.

Sample Usage

<form>
    <input type="text" name="txt01[][name]" value="Text 01" />
    <input type="text" name="txt01[][phone]" value="000001" />

    <input type="text" name="txt01[][name]" value="Text 02" />
    <input type="text" name="txt01[][phone]" value="000002" />

    <input type="submit" value="Submit" />
</form>

<script>
    ( function( $){
        $( document ).ready( function(){
            $( "form" ).submit( function( e ) {
                e.preventDefault();

                var jsonObject = $( this ).serializeObject();
                console.log( jsonObject );
            } );
        } );
    } )( jQuery );
</script>

Console Output

Object 
{
    txt01: Array(2) 
    {
        0: Object
        {
            name: Text 01
            phone: 000001
        },

        1: Object
        {
            name: Text 02
            phone: 000002
        }
    }
}

For more details click here.

Neil Villareal
  • 627
  • 9
  • 14
1

Try serialize() or serializeArray() instead serializeObject()

Ba.Lal
  • 180
  • 2
  • 16