Sunday, August 5, 2012

Send POST or GET data to a page from javascript

I found and modified this. It is a javascript function that dynamically creates a form and sends the data via POST or GET to the page.  Enjoy.

The params variable needs you to send data in a key value array object. 

pass = { postThis: 'Posted', andThis: 'as well' };
post_to_url('index.php', pass, 'post');


function post_to_url(path, params, method)
            {
                method = method || "post";

                var form = document.createElement("form");

                form.setAttribute("method", method);
                form.setAttribute("action", path);

                for(var key in params) {
                    var hiddenField = document.createElement("input");
                    hiddenField.setAttribute("type", "hidden");
                    hiddenField.setAttribute("id", key);
                    hiddenField.setAttribute("name", key);
                    hiddenField.setAttribute("value", params[key]);

                    form.appendChild(hiddenField);
                }
                document.body.appendChild(form);
                form.submit();
            }


<?php
echo $_POST['postThis'];  //Posted
echo $_POST['andThis'];  //as well
?>

No comments:

Post a Comment