Skip to content
Advertisement

Non-AJAX jQuery POST request

I am trying to use the jQuery POST function but it is handling the request in AJAX style. I mean it’s not actually going to the page I am telling it to go.

$("#see_comments").click(function() {
    $.post(
        "comments.php", 
        {aid: imgnum}, 
        function (data) {

        }
    );
});

This function should go to comments.php page with the aid value in hand. It’s posting fine but not redirecting to comments.php.


@Doug Neiner Clarification:

  1. I have 15 links (images). I click on a link and it loads my JavaScript. The script knows what imgnum I opened. This imgnum I want in the comments.php. I have to use this JavaScript and no other means can do the trick. The JavaScript is mandatory

  2. Your method successfully POSTs the aid value. But in the comments.php when I try to echo that value, it displays nothing.

  3. I am using Firebug. In the Console, it shows the echo REQUEST I made in Step (2) successfully.

Advertisement

Answer

I know what you are trying to do, but its not what you want.

First, unless you are changing data on the server, don’t use a POST request. Just have #see_comments be a normal <a href='/comments.php?aid=1'>...

If you have to use POST, then do this to get the page to follow your call:

$("#see_comments").click(function() {
  $('<form action="comments.php" method="POST">' + 
    '<input type="hidden" name="aid" value="' + imgnum + '">' +
    '</form>').submit();
});

How this would actually work.

First $.post is only an AJAX method and cannot be used to do a traditional form submit like you are describing. So, to be able to post a value and navigate to the new page, we need to simulate a form post.

So the flow is as follows:

  1. You click on the image, and your JS code gets the imgnum
  2. Next, someone clicks on #see_comments
  3. We create a temporary form with the imgnum value in it as a hidden field
  4. We submit that form, which posts the value and loads the comments.php page
  5. Your comments.php page will have access to the posted variable (i.e. in PHP it would be $_POST['aid'])
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement