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.
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'
});
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' },
]);
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With