jquery - submit post synchronously (not ajax)

olamundo picture olamundo · Oct 2, 2010 · Viewed 12.9k times · Source

I have a page (page 1) that accepts post requests, does some stuff and displays some data at the end.

From another page (page 2), I want to redirect to page 1 when a button is clicked, of course sending all relevant data required by page 1 via POST.

I can, of course, use the old hack of having an invisible form on the page, stuffing in all the data I need using jquery, just after the user clicked the button, and submit() it automatically. But that looks cumbersome - it's much nicer to use syntax similar to $.post, rather than starting to manipulate html. $.post would be perfect, were it to actually redirect to the page and not make the request asynchronously (I can't just redirect to page 1 after the ajaxy post has completed since page 1 needs the data to display something).

Is there some way to do what I want with jquery, or are ugly invisible forms the only way out?

P.S

I know there are other convoluted ways of achieving what I want, for instance using $.post and just planting the respond's html in the page we're currently on, but I just want to know if there's a straightforward way of doing this with jquery

Answer

Greg W picture Greg W · Oct 2, 2010

This gave me an idea for a little jQuery function to mimic the $.post behavior as you described. It still uses invisible forms in the background, but the syntax for it is relatively clean and straightforward.

$(document).ready(function(){
    $('#myButton').PostIt('post.php', {foo:'bar', abc:'def', life:42});
    $('#myOtherButton').PostIt('post.php', dataObjectFromSomewhereElse);
});

$.fn.PostIt = function(url, data){

  $(this).click(function(event){

        event.preventDefault();

        $('body').append($('<form/>', {
          id: 'jQueryPostItForm',
          method: 'POST',
          action: url
        }));

        for(var i in data){
          $('#jQueryPostItForm').append($('<input/>', {
            type: 'hidden',
            name: i,
            value: data[i]
          }));
        }

        $('#jQueryPostItForm').submit();
    });
}