1

What's the standard or most popular way of changing or adding a form values being serialized and sent to the server on form submit? I need to just change / add them before they are have been sent.

I found some solutions, but they all seemed to be just hacks. For instance, this one creates these values again which is not wise. In my case, I don't want to recreate them if possible.

var serial = new Array();
var i = 0;
$('.om input').each( function(){
    serial[i++] = $(this).attr('name')[0]+'='+$(this).html()[0];
});
serial.join('&');
Incerteza
  • 32,326
  • 47
  • 154
  • 261
  • Best example : http://jsfiddle.net/sxGtM/3/ – Ash Jul 11 '14 at 06:42
  • http://stackoverflow.com/a/1186309/3660930 – Ash Jul 11 '14 at 06:42
  • @user972, where is it shown how to **capture** and change the data? – Incerteza Jul 11 '14 at 06:54
  • In the fiddle, please see the JavaScript section where it handles the form submit. It captures the data via this.serializeArray() and then uses push function to add extra values. You can take reference from this example. – Ash Jul 13 '14 at 23:26

1 Answers1

0

Try this,

<html>
<head>

<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.1.min.js"></script>

    <script type="text/javascript">
        function submitForm()
        {
            var queryParam = $("#myform").serialize();
            var inputArr = queryParam.split("&");
            var retObj = {};
            $.each(inputArr,function(key,value){
                retObj[value.split("=")[0]] = value.split("=")[1];
            });
            retObj.input1 = "newOne";
            retObj.newAttr = "newlyAddedValue";
            alert(jsObjToQueryStr(retObj));
        }

        function jsObjToQueryStr(jsonObj)
        {
            var retStr = "";
            $.each(jsonObj,function(key,value){
                retStr += key+"="+value+"&";
            });
            if( retStr.length > 0 )
            {
                return retStr.substr(0,retStr.length-1);
            }
            return retStr;
        }

    </script>
</head>
<body>

<form id="myform" >
    <input type="test" name="input1"/>
    <input type="test" name="input2"/>
    <input onclick="submitForm()" type="button" value="submit"/>
</form>

</body>
</html>