Search code examples
jquery-post

Jquery $.post doesn't work


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" });

}

Solution

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