Serialize form in a "hash format"
Asked Answered
A

2

6

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.

Abduction answered 16/12, 2010 at 9:18 Comment(1)
NOTICE: When submitting as hash, info about order of form elements is lostWelch
A
6

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());
}
Abduction answered 16/12, 2010 at 10:6 Comment(0)
S
3

The solution given by Javi can match most cases except if you have inputs with names like "inputname[key]". You will get a javascript key {"inputname[key]": value} except of {"inputname": {"key": value} }. I suggest to use the jquery plugin jquery.serialize-hash.

https://github.com/sdrdis/jquery.serialize-hash

Stirring answered 15/5, 2012 at 8:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.