Concept: Simulating POST and GET Requests with JavaScript

After reading this title, you’re probably thinking “why would I EVER need to do that?” The answer is probably never in a practical situation. It could be employed in slightly less-than-ethical areas such as XSS attacks. It could be employed in quick data transfer through a multipage form. Of course, if you’re doing that you likely have a framework of some sort doing it for you in the background. Or, maybe you’re writing one of those kinds of frameworks. In my case, it’s part of a larger idea to simulate a “server” in cPHP–a (very) experimental client-side PHP->JavaScript translator/compatibility layer thing. Since cPHP itself is AJAX-based, and the JavaScript engine needs to control the entire translation and execution of the script, it needs to be able to maintain data between form submissions and provide to its PHP implementation a reliable “illusion” of a server.

There isn’t really any code in this post (that will hopefully come some day later); it’s just a few different ideas on how this could work. The first idea that crossed my mind was to allow form submissions to work as normal; as they are specified in the HTML. We could parse the querystring (the URL in the address bar) to get all of the information we need. This is probably the simplest approach, but it has severe limitations. Firstly, POST requests would not work at all as JavaScript is not aware of what is POSTed to a server. In my case, I don’t even care about the server. Secondly, the page will reload, which may require forwarding of other state information between the two pages.

My other idea is more complicated. The JavaScript, when loading the page, will actually inspect the form tag(s) in the document, modify them so that no request is sent, but find its submit inputs and create a function that “submits” the form, recording data internally. In the case of cPHP, it would be easy from this point to populate the $_POST associative array or $_GET associative array, depending on the original method attribute specified by the form tag.