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.
Rakesh Pai's answer is amazing, but there is an issue that occurs for me (in Safari) when I try to post a form with a field called
submit
. For example,post_to_url("http://google.com/",{ submit: "submit" } );
. I have patched the function slightly to walk around this variable space collision.No, you cant have the JavaScript post request like a form submit.
What you can have is a form in HTML, then submit it with the JavaScript. (as explained many times on this page)
You can create the HTML yourself, you don't need JavaScript to write the HTML. That would be silly if people suggested that.
Your function would just configure the form the way you want it.
Then, use it like.
But I would just leave out the function and just do.
Finally, the style decision goes in the ccs file.
Personally I think forms should be addressed by name but that is not important right now.
This works perfectly in my case:
You can use it in function like:
Using this you can post all the values of inputs.
My solution will encode deeply nested objects, unlike the currently accepted solution by @RakeshPai.
It uses the 'qs' npm library and its stringify function to convert nested objects into parameters.
This code works well with a Rails back-end, although you should be able to modify it to work with whatever backend you need by modifying the options passed to stringify. Rails requires that arrayFormat be set to "brackets".
Example:
Produces these Rails parameters:
You could dynamically add the form using DHTML and then submit.
Here is how I do it.