views:

55

answers:

3

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

A: 

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.com?name=hello&amp;id=11111
 * z = gup('name', window.location.href); // z = hello
 * Original code from Netlobo.com (http://www.netlobo.com/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];
}
fudgey
data needs to be received server side, and I'm being told it a) has to be post data, and b) the server side code can't/won't be modified. Guess I'm going with invisible form and `.submit()`
Will
If you are using php, you can use GET to get the "name" value as well.
fudgey
+2  A: 

What 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.

CD Sanchez
I had originally created a hidden form, but I'm going to rewrite it to use use this method -- very slick.
Will
+2  A: 

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>
fehays
Good suggestion, and this was my inital solution, but I think the accepted answer takes this and refines it.
Will