I'm trying to direct a browser to a different page. If I wanted a GET request, I might say
document.location.href = 'http://example.com/q=a';
But the resource I'm trying to access won't respond properly unless I use a POST request. If this were not dynamically generated, I might use the HTML
<form action="http://example.com/" method="POST">
<input type="hidden" name="q" value="a">
</form>
Then I would just submit the form from the DOM.
But really I would like JavaScript code that allows me to say
post_to_url('http://example.com/', {'q':'a'});
What's the best cross browser implementation?
Edit
I'm sorry I was not clear. I need a solution that changes the location of the browser, just like submitting a form. If this is possible with XMLHttpRequest, it is not obvious. And this should not be asynchronous, nor use XML, so Ajax is not the answer.
this is the answer of rakesh, but with support for arrays (which is quite common in forms):
plain javascript:
oh, and here's the jquery version: (slightly different code, but boils down to the same thing)
A simple quick-and-dirty implementation of @Aaron answer:
Of course, you should rather use a JavaScript framework such as Prototype or jQuery...
Here is how I wrote it using jQuery. Tested in Firefox and Internet Explorer.
The easiest way is using Ajax Post Request:
where:
Then in the success handler redirect the browser with something like window.location.
Yet another recursive solution, since some of others seem to be broken (I didn't test all of them). This one depends on lodash 3.x and ES6 (jQuery not required):
This is based on beauSD's code using jQuery. It is improved so it works recursively on objects.