35

This is one of those situations where I feel like I'm missing a crucial keyword to find the answer on Google...

I have a bag of parameters and I want to make the browser navigate to a GET URL with the parameters. Being a jQuery user, I know that if I wanted to make an ajax request, I would simply do:

$.getJSON(url, params, fn_handle_result);

But sometimes I don't want to use ajax. I just want to submit the parameters and get a page back.

Now, I know I can loop the parameters and manually construct a GET URL. For POST, I can dynamically create a form, populate it with fields and submit. But I'm sure somebody has written a plugin that does this already. Or maybe I missed something and you can do it with core jQuery.

So, does anybody know of such a plugin?

EDIT: Basically, what I want is to write:

$.goTo(url, params);

And optionally

$.goTo(url, params, "POST");
itsadok
  • 28,822
  • 30
  • 126
  • 171

7 Answers7

51

jQuery Plugin seemed to work great until I tried it on IE8. I had to make this slight modification to get it to work on IE:

(function($) {
    $.extend({
        getGo: function(url, params) {
            document.location = url + '?' + $.param(params);
        },
        postGo: function(url, params) {
            var $form = $("<form>")
                .attr("method", "post")
                .attr("action", url);
            $.each(params, function(name, value) {
                $("<input type='hidden'>")
                    .attr("name", name)
                    .attr("value", value)
                    .appendTo($form);
            });
            $form.appendTo("body");
            $form.submit();
        }
    });
})(jQuery);
Dustin
  • 526
  • 5
  • 3
  • Excellent, but I was a little in the dark on how to use this for posting the input values of another form on the page. In the end I used it with the http://stackoverflow.com/questions/1131630/javascript-jquery-param-inverse-function#1131658 unparam function by blixt like so: $.postGo('/my/post/handler', jQuery.unparam($('#myform').serialize())); – James McCormack Sep 10 '10 at 14:29
  • 3
    Note: the jQuery plugin Dustin's referring to is by itsadok (see below). That confused me at first. ;-) – Simon East Sep 20 '11 at 04:28
  • 1
    nice! Also if you want to support arrays passed as values, then you have to update `postGo` method (`getGo` works ok already): add check `if (value instanceof Array)` inside `function(name, value) {` of `each` loop and in case value IS array - iterate over it, appending inputs with value `values[i]`. In case value IS NOT an array - use already present code. – pavel_kazlou Dec 16 '11 at 10:23
  • 1
    @JamesMcCormack This solution is most useful if you don't have a form beforehand. If you already have a form, then most of the time you can just [`.submit()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement.submit) it. Using `serialize` then `unparam` is a bit roundabout. – Kos Jul 22 '13 at 13:53
20

Here's what I ended up doing, using the tip from redsquare:

(function($) {
    $.extend({
        doGet: function(url, params) {
            document.location = url + '?' + $.param(params);
        },
        doPost: function(url, params) {
            var $form = $("<form method='POST'>").attr("action", url);
            $.each(params, function(name, value) {
                $("<input type='hidden'>")
                    .attr("name", name)
                    .attr("value", value)
                    .appendTo($form);
            });
            $form.appendTo("body");
            $form.submit();
        }
    });
})(jQuery);

Usage:

$.doPost("/mail/send.php", {
    subject: "test email",
    body: "This is a test email sent with $.doPost"
});

Any feedback would be welcome.

Update: see dustin's answer for a version that works in IE8

itsadok
  • 28,822
  • 30
  • 126
  • 171
  • without $form.appendTo("body"); it will not work in IE9. Thanks ! I was having a problem with this – fredcrs Jul 06 '12 at 13:42
12

It is not clear from the question if you have a random bunch of values you want to pass on the querystring or is it form values.

For form values just use the .serialize function to construct the querystring.

e.g

var qString = $('#formid').serialize();
document.location = 'someUrl' + '?' + serializedForm

If you have a random bunch of values you can construct an object and use the .param utility method.

e.g

 var params = { width:1680, height:1050 };
 var str = jQuery.param( params );
 console.log( str )
 // prints width=1680&height=1050
 // document.location = 'someUrl' + '?' + str
redsquare
  • 78,161
  • 20
  • 151
  • 159
3

FYI for anyone doing the doPost for rails 3, you need to add in the CSRF token, Adding the following to the answer should do that...

var token = $('meta[name="csrf-token"]').attr('content');
$("<input name='authenticity_token' type='hidden' value='" + token + "'/>").appendTo($form);
Jim Morris
  • 2,870
  • 24
  • 15
  • 1
    Yes, certain other server-side technologies (Drupal and Django come to mind) will require some hidden security-related fields like this too. – Simon East Sep 20 '11 at 04:33
1

This is similar to the above except it will handle Array parameters being passed to MVC

(function($) {
    $.extend({
        getGo: function(url, params, traditional) {
            /// <summary>
            ///     Perform a GET at url with specified params passed as part of the query string.
            /// </summary>
            /// <param name="url"></param>
            /// <param name="params"></param>
            /// <param name="traditional">Boolean:  Specify true for traditional serialization.</param>
            document.location = url + '?' + $.param(params, traditional);
        },
        postGo: function (url, params) {
            /// <summary>
            ///     Perform a POST at url with the specified params as part of a form object.
            ///     If a parameter is an array then it will submit it as multiple attributes so MVC will see it as an array
            /// </summary>
            /// <param name="url" type="string"></param>
            /// <param name="params" type="Object"></param>
            var $form = $("<form>").attr("method", "post").attr("action", url);
            $.each(params, function (name, value) {
                if (value.length != null && value.length > 0) {
                    for (var i = 0; i < value.length; i++) {
                        $("<input type='hidden'>").attr("name", name + '[' + i + ']').attr("value", value[i]).appendTo($form);
                    }
                }
                else {
                    $("<input type='hidden'>").attr("name", name).attr("value", value).appendTo($form);
                }
            });
            $form.appendTo("body");
            $form.submit();
        }
    });
})(jQuery);
zlsmith86
  • 380
  • 4
  • 11
  • ++, but note that (at least as of MVC 6 - not sure about earlier versions) you needn't modify the `name` value with an index - multiple elements of the very same name will do to be recognized as an array. Also, perhaps substituting `$.isArray(value)` for `value.length != null && value.length > 0` makes the code more readable. – mklement0 Apr 12 '16 at 20:53
0

Good job itsadok! If you want a invisible form put it into hidden DIV:

(function($) {
    $.extend({
        doGet: function(url, params) {
            document.location = url + '?' + $.param(params);
        },
        doPost: function(url, params) {
            var $div = $("<div>").css("display", "none");
            var $form = $("<form method='POST'>").attr("action", url);
            $.each(params, function(name, value) {
                $("<input type='hidden'>")
                    .attr("name", name)
                    .attr("value", value)
                    .appendTo($form);
            });
            $form.appendTo($div);
            $div.appendTo("body");
            $form.submit();
        }
    });
})(jQuery);
piper
  • 1
  • 1
    Yeah, or you can just set the
    to `display: none`. A form with only hidden fields shouldn't display anything, however - except maybe a little empty space from the margin/padding (in certain browsers).
    – Simon East Sep 20 '11 at 04:31
-5

The accepted answer doesn't seem to cover your POST requirement, as setting document.location will always result in a GET request. Here's a possible solution, although I'm not sure jQuery permits loading the entire contents of the page like this:

$.post(url, params, function(data) {
  $(document).html(data);
}, "html");
toluju
  • 4,097
  • 2
  • 23
  • 27
  • 2
    I wasn't the one who downvoted you. But a .post is AJAX. He wanted non-AJAX so it would actually change the page. – Rap Nov 25 '09 at 14:53