Wednesday, December 22, 2010

get2post (get request to post request conversion)

Sometimes for some reasons there is the need to convert a get request to a post request when the target site accepts only post requests. There is a simple way to do this with javascript by creating a form on the fly and posting it.

The function function get2post(requestUrl, target) can be called in this way:
get2post('http://www.yoururl.com?param1=value1&param2=value2');

or, you can specify a popup window or target by calling it in this way:
open('about:blank','Popup','resizable=yes,width=1015,height=700,scrollbars=yes');
get2post('http://www.yoururl.com?param1=value1&param2=value2', 'Popup');

You can look at the test page over here: get2post

In order to use this function, copy and paste the script below to your html site.
<script>
/* Author: Redi Gokaj
* Description: This function transforms a get request into a post request using javascript.
* http://www.redigokaj.com
*/

function get2post(requestUrl, target)
{
if (target == null) target = '_parent';

var postUrl = requestUrl.split("?")[0];
var parameters = requestUrl.split("?")[1].split("&");

var postForm = document.createElement("form");
document.body.appendChild(postForm);
postForm.setAttribute("action", postUrl);
postForm.setAttribute("method", "post");
postForm.setAttribute("target", target);
postForm.style.display = "none";

for (i = 0; i < parameters.length; i++)
{
var formElement = document.createElement("input");
var name = parameters[i].split("=")[0];
var value = parameters[i].split("=")[0];

formElement.name = name;
formElement.value = value;
postForm.appendChild(formElement);
}

postForm.submit();
}

</script>