Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .serializeObject is not a function - only in Firefox

Tags:

jquery

firefox

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.

like image 663
Wasim Avatar asked Jan 17 '12 19:01

Wasim


2 Answers

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

like image 157
Rafay Avatar answered Sep 19 '22 12:09

Rafay


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.

like image 34
Neil Villareal Avatar answered Sep 21 '22 12:09

Neil Villareal