Jquery $.post doesn't work

4.9k Views Asked by At

Is there a trick to making this function work?

I want the page to be submitted to test.aspx upon button clicking and POST param in the following way:

my html

<a href="javascript:void(0);" onclick="return submittotest();"><span>Click me</span></a>

js

function submittotest() {

     $.post("test.aspx", { param: "paramvalue" });

}
2

There are 2 best solutions below

1
On BEST ANSWER

If you want to submit a form, you need to do $('#formid').submit();. What you have above is for an AJAX request. You need to pass a success callback function to the post function if you want to do something with the returned data.

Example: See here

HTML

<button id="testbtn">button</button>
<div id="testdiv"></div>

JavaScript

$(function() {
    $('#testbtn').click(function() {
        $.post('/echo/html/', //This just echo's the html parameter's value back
               { html: "Just testing!" },
               function(text) {
                   $("#testdiv").html(text);
               });
    });
});

Edit
Based on your comments. You can add a hidden input element with the value you want to the form using jquery. Try something like this:

var yourdatavar = "data you want to post";
$('<input type="hidden">').val(yourdatavar).appendTo('#formid');
$('#formid').submit();

Check out this for a working example.

0
On

Try this, it will submit an invisible form to test.apsx page with the desired parameter.

<form id="formToSubmit" action="test.apsx" method="post" style="display:none;">
  <input type="hidden" name="param" value="paramValue"/>
</form>

<a href="#" onclick="$('#formToSubmit').submit();">Submit the page</a>