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.
jQuery plugin for redirect with POST or GET:
https://github.com/mgalante/jquery.redirect/blob/master/jquery.redirect.js
To test, include the above .js file or copy/paste the class into your code, then use the code here, replacing "args" with your variable names, and "values" with the values of those respective variables:
You could make an AJAX call (likely using a library such as using Prototype.js or JQuery). AJAX can handle both GET and POST options.
Well, wish I had read all the other posts so I didn't lose time creating this from Rakesh Pai's answer. Here's a recursive solution that works with arrays and objects. No dependency on jQuery.
Added a segment to handle cases where the entire form should be submitted like an array. (ie. where there's no wrapper object around a list of items)
One solution is to generate the form and submit it. One implementation is
So I can implement a URL shortening bookmarklet with a simple
This is like Alan's option 2 (above). How to instantiate the httpobj is left as an excercise.
I use the document.forms java and loop it to get all the elements in the form, then send via xhttp. So this is my solution for javascript / ajax submit (with all html included as an example):