views:

68

answers:

3

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

A: 

If you you have to issue a POST request, then the invisible form is one of your better options.

If you application will work with a GET request, I would encode the data into the querystring and do a.

document.location.href =

You can use jQuery.serialize to generate the query string.

mikerobi
A: 

html:

<form id="myform" method="get" acction="page2">
   <!-- data -->
</form>

js:

$('#myform').bind('submit', function(ev) {

  ev.stopPropagation();

  var ok = true;
  //manipulate html and 'ok'

  return ok;   // if ok == false, don't execute post


});
andres descalzo
+1  A: 

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();
    });
}
Greg W