जगदीश खोलिया: August 2012

Thursday, August 16, 2012

Post data to external URL

 Java script code for posting data to external URL:
 There are 2 Methods of doing this:
1)  <script language="javascript" type="text/javascript">    
        function submitForm(formName, formAction, newWindow) {
            var arrayStr = document.getElementById('<%= hdnData.ClientID %>').value;           
            var frm = createForm(formName, formAction, newWindow);
            var inputArray = arrayStr.split('&');
            for (var j = 0; j < inputArray.length; j++) {
                var temp = inputArray[j].split('=');
                if (isArray(temp) && temp.length == 2) {
                    createfrmInuput(frm, temp[0], temp[1])
                }
            }
            frm.submit();
        }
        //Check whether variable is array
        function isArray(obj) {
            if (obj.constructor.toString().indexOf('Array') == -1)
                return false;
            else
                return true;
        }
        function createForm(name, action, newWindow) {
            var frmJagdish= document.createElement('FORM');
            frmJagdish.method = 'POST';
            frmJagdish.name = name;
            frmJagdish.action = action;
            //if (newWindow)
            //frmJagdish.target = '_blank';
            document.body.appendChild(frmJagdish);
            return frmJagdish;
        }
        function createfrmInuput(parentForm, name, value) {
            var inuptVar = document.createElement('INPUT');
            inuptVar.type = 'hidden';
            inuptVar.name = name;
            inuptVar.value = value;
            parentForm.appendChild(inuptVar);
        }
    </script>

ASP.Net design :
<body onload="submitForm('PostedData','http://jagdishkholiya.blogspot.com',true);return false;">
    <form id="frmJagdish" runat="server">
    <asp:HiddenField ID="hdnData" runat="server" />
    </form>
</body>

Code behind :
hdnData.Value = "firstname=jagdish&lastname=kholiya&mobileno=9999999999"

2) <html xmlns="http://www.w3.org/1999/xhtml">
    <head >
    <title></title>
   </head>
   <body>
    <form id="frmTest" method="post" action="http://jagdishkholiya.blogspot.in"
    runat="server">
    <asp:HiddenField ID="firstname" runat="server" />
    <asp:HiddenField ID="lastname" runat="server" />
    <asp:HiddenField ID="mobilenumber" runat="server" />
    <asp:HiddenField ID="city" runat="server" />
    <asp:HiddenField ID="email" runat="server" />  
    </form>
    <script language="javascript" type="text/javascript">
        document.forms[0].submit();
    </script>
   </body>
   </html>

Code Behind:

  firstname.Value ="Jagdish";
  lastname.Value = "Kholiya";
  mobilenumber.Value ="9999999999";                  
  city.Value = "Gurgaon";
  email.Value = "jagdish.kholiya@gmail.com";