32

Is there a simple non-AJAX POST method in jQuery?

I am looking for something equivalent to a form on a page with nothing but hidden fields set via JavaScript which then gets POST-ed, causing the browser to load the page set via action. Just a normal POST, but with values set via jQuery.

I suppose I could keep implementing my current method, but I am curious if jQuery provides a quick way. In the background, I imagine it would dynamically create this form with all of the hidden values and submit it.

Brad
  • 159,648
  • 54
  • 349
  • 530
  • possible duplicate of [Non-ajax GET/POST using jQuery (plugin?)](http://stackoverflow.com/questions/1149454/non-ajax-get-post-using-jquery-plugin) – Jacob Apr 02 '11 at 15:26

5 Answers5

40

Tidied Darin's excellent solution slightly.

function myFunction(action, method, input) {
    'use strict';
    var form;
    form = $('<form />', {
        action: action,
        method: method,
        style: 'display: none;'
    });
    if (typeof input !== 'undefined' && input !== null) {
        $.each(input, function (name, value) {
            $('<input />', {
                type: 'hidden',
                name: name,
                value: value
            }).appendTo(form);
        });
    }
    form.appendTo('body').submit();
}

This is JSLint-compatible and makes sure that no form is displayed at the end of body tag despite possible css definitions. The usage is also slightly more straightforward, e.g:

myFunction('/path/to/my/site/', 'post', {
    id: 1,
    quote: 'Quidquid Latine dictum sit altum videtur'
});
Anssi Herranen
  • 569
  • 6
  • 12
40

There is nothing built-in. You could create a dynamic form populating it with hidden fields, add it to the DOM and trigger a submit. Here's an example:

function submit(action, method, values) {
    var form = $('<form/>', {
        action: action,
        method: method
    });
    $.each(values, function() {
        form.append($('<input/>', {
            type: 'hidden',
            name: this.name,
            value: this.value
        }));    
    });
    form.appendTo('body').submit();
}

submit('http://www.example.com', 'POST', [
    { name: 'key1', value: 'value1' },
    { name: 'key2', value: 'value2' },
    { name: 'key3', value: 'value3' },
]);
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Thanks for the solution! It was very helpful in my attempt to protect a Delete action in ASP.NET MVC by marking it as POST. – Luis Aguilar Apr 20 '11 at 04:33
  • +1 darin, late in the day in finding this but still relevant for a requirement i had today!! thanks – jim tollan Apr 17 '12 at 13:17
  • @trinth Most of the useful things does not work in IE, however this is a very useful solution. – Clain Dsilva Nov 20 '13 at 13:25
  • 1
    @ClainDsilva: agree it's useful, however, others may want to know the caveats before having to find out themselves – trinth Nov 20 '13 at 22:23
  • @trinth I dno't see any reason why it wouldn't work in IE9, unless the issue is that trailing comma in the data. If that's what you're using for data, just get rid of that trailing comma. – Brad Jun 12 '14 at 19:07
  • no need for the `method` argument since a GET would simply use `location.window.href = URL_HERE` – JoshuaDavid Dec 30 '14 at 17:19
  • I don't really understand why this isn't the accepted answer. – James Jun 10 '15 at 10:39
8

I found these answers very useful, and have modified Anssi Herranen's solution to also post arrays to server-side php correctly:

function jqueryPost(action, method, input) {
    "use strict";
    var form;
    form = $('<form />', {
        action: action,
        method: method,
        style: 'display: none;'
    });
    if (typeof input !== 'undefined') {

        $.each(input, function (name, value) {

            if( typeof value === 'object' ) {

                $.each(value, function(objName, objValue) { 

                    $('<input />', {
                        type: 'hidden',
                        name: name + '[]',
                        value: objValue
                    }).appendTo(form);
                } );      
            }
            else {

                $('<input />', {
                    type: 'hidden',
                    name: name,
                    value: value
                }).appendTo(form);
            }
        });
    }
    form.appendTo('body').submit();
}
Corie Slate
  • 616
  • 9
  • 19
Mark B
  • 528
  • 5
  • 7
  • 2
    I don't understand why this was down voted. This should be the correct answer. I wish I would have seen it first, because the array was a problem I dealt with for 30 minutes before coming back and seeing this. – taelor May 12 '14 at 18:54
  • Agreed, this allows to post arrays, the accepted answer doesn't. – Xeaz Jul 12 '14 at 13:26
3

The author asked for a jQuery solution, but this can just as easily be done with plain JavaScript:

function post (action, nameValueObj){
    var form = document.createElement("form");
    var i, input, prop;
    form.method = "post";
    form.action = action;
    for (prop in nameValueObj) { // Loop through properties: name-value pairs
        input = document.createElement("input");
        input.name = prop;
        input.value = nameValueObj[prop];
        input.type = "hidden";
        form.appendChild(input);
    }
    //document.body.appendChild(form); <-- Could be needed by some browsers?
    form.submit();
    return form;
}
// Example usage:
post("actionPage.html", {
    "field1": "hello",
    "field2": "world" 
    /* etc. */
});
Luke
  • 18,811
  • 16
  • 99
  • 115
-5

i think you can use something like:

paramters = {key1: 'value1', key2: 'value2'}

jQuery.ajax({ 
   url:'/your/url', 
   data: jQuery.param(paramters),
   async:false,
   type:'POST',
   success: function(result){
       doSomethingWithYourResult(result);
   }
})

Note the 'asyn=false' setting

bicccio
  • 384
  • 1
  • 19
  • 3
    @biccio, this won't work. This is still AJAX, it just blocks until the request finishes. – Brad Apr 02 '11 at 18:46
  • @Brad it work well!!! it does a syncronous POST call to the server, passing every values you want like a form with hidden fields. The function is ajax but it doesn't works like ajax, it works syncronously like a form... – bicccio Apr 02 '11 at 20:23
  • 4
    @biccio, Yes I understand that, but I want something that completely reloads the page at the same time. This method doesn't do that. This is a fine solution for some things, but not for my application. – Brad Apr 02 '11 at 21:14