I'm not even sure if this is possible, but I need to send POST data to a page via a user-clicked link. Can this be done?
To be clear, I do not want the data returned to the current page; the target page should load in the browser just as though the user had submitted a form, but I need to send the post data without a form, if possible
I'm not even sure if this is possible, but I need to send POST data to a page via a user-clicked link. Can this be done?
To be clear, I do not want the data returned to the current page; the target page should load in the browser just as though the user had submitted a form, but I need to send the post data without a form, if possible
Share Improve this question edited Sep 15, 2010 at 21:58 Will asked Sep 15, 2010 at 21:49 WillWill 5,6109 gold badges38 silver badges51 bronze badges3 Answers
Reset to default 5What do you mean without a form? Can the form be "invisible" to the user? If so, you could do something like:
$("a.post").click(function (e) {
e.preventDefault();
$("<form action='"+this.href+"' method='post'></form>").submit();
});
Obviously it could be done many different ways, but you get the idea.
It would be just like a form with the POST parameters intact in the request just in case you use that information at the server when serving up that page.
How about a form with a hidden input? Just create a click event on the anchor tag that submits the form:
<script type="text/javascript">
$(function () {
$("#postLink").click(function () {
$("#form").submit();
});
});
</script>
<a id="postLink" href="javascript:;;">click to post</a>
<form id="form" action="[postTargetUrl]" method="post">
<input type="hidden" name="postVariable" value="[postValue]" />
</form>
I would just add the data to the url, then the target page can extract it:
Main Page:
<a href="page2.htm?name=Fred">Fred</a>
Target page (page2.htm)
$(document).ready(function(){
var name = gup("name", window.location.href);
alert(name);
});
/* Returns URL parameter
* url: http://www.somesite.?name=hello&id=11111
* z = gup('name', window.location.href); // z = hello
* Original code from Netlobo. (http://wwwlobo./url_query_string_javascript.html)
*/
function gup(n,s){
n = n.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");
var p = (new RegExp("[\\?&]"+n+"=([^&#]*)")).exec(s);
return (p===null) ? "" : p[1];
}