Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize form in a "hash format"

In the documentation of jeditable for the submitdata param (a parameter to include some extra params in the ajax request) it is said:

(Mixed) submitdata: Extra parameters when submitting content. Can be either a hash or function returning a hash.

 $(".editable").editable("http://www.example.com/save.php";,
     {    
         submitdata : {foo: "bar"}; 
 });

 $(".editable").editable("http://www.example.com/save.php";,
     {    
         submitdata : function(value, settings) {
             return {foo: "bar"};    
     } 
 });

So I need to include in the submitData some params which I recover from the serialization of a form:

<form id="myForm">
     <input type="hidden" name="param1" value="myValue1"/>
     <input type="hidden" name="param2" value="myValue2"/>
</form>

so when I prepare the submitdata I do:

submitdata : function(value, settings){
    return $("#myForm").serializeArray();
}

The problem is that serialize the form in this way results in a format like :

[Object { name="param1", value="myValue1"}, Object { name="param2", value="myValue2"}]

but jeditable doesn't understand it and it sends in the request

0[name] param1
0[value]    myValue1
1[name] param2
1[value]    myValue2

I have tried with serialize() function but it doesn't understand it either because Jeditable requires something like:

{param1: "value1" , param2: "value2"}

Is there any way to serialize the form in the jeditable required format or a quick way to change the format after the serialization?

Thanks.

like image 242
Javi Avatar asked Dec 16 '10 09:12

Javi


1 Answers

I can solve it building an object from the serialized array, though I don't know if it would be the best way to do this.

submitdata : function(value, settings){
    var reformat = function(array){
        var obj = {};
        for(i=0; i<array.length; i++){
            var a = array[i];
            var name = a.name;
            var value = a.value;
            obj[name] = value;
        }
        return obj;
    };
    return reformat($("#myForm").serializeArray());
}
like image 114
Javi Avatar answered Oct 10 '22 03:10

Javi