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.
The method I use to post and direct a user automatically to another page is to just write a hidden form and then auto submit it. Be assured that the hidden form takes absolutely no space on the web page. The code would be something like this:
Application of auto submit
An application of an auto submit would be directing form values that the user automatically put in on the other page back to that page. Such an application would be like this:
The Prototype library includes a Hashtable object, with a ".toQueryString()" method, which allows you to easily turn a JavaScript object/structure into a query-string style string. Since the post requires the "body" of the request to be a query-string formatted string, this allows your Ajax request to work properly as a post. Here's an example using Prototype:
Three options here.
Standard JavaScript answer: Use a framework! Most Ajax frameworks will have abstracted you an easy way to make an XMLHTTPRequest POST.
Make the XMLHTTPRequest request yourself, passing post into the open method instead of get. (More information in Using POST method in XMLHTTPRequest (Ajax).)
Via JavaScript, dynamically create a form, add an action, add your inputs, and submit that.
I'd go down the Ajax route as others suggested with something like:
This would be a version of the selected answer using jQuery.
If you have Prototype installed, you can tighten up the code to generate and submit the hidden form like this: