Replacement function for jQuery .post
Today I just completed a personal POST function that emulates jQuery's using $.ajax, but also implementing a possible redirect. I just finished up and it looks like it is functional, but since this is something I want to keep long term and integrate in many projects, I want to make sure it is as functional as possible.
function postR(url, params, redir = false, callback = null) {
if(redir){
var form = document.createElement('form');
form.method = 'post';
form.action = url;
for (var key in params) {
var input = document.createElement('input');
input.type = 'hidden';
input.name = key;
input.value = params[key];
form.appendChild(input);
}
document.body.appendChild(form);
form.submit();
}else{
if(callback && typeof(callback) === "function"){
$.ajax({
type: "POST",
url: url,
data: params,
success: function(data){
callback(data)
}
});
}else{
$.ajax({
type: "POST",
url: url,
data: params
});
}
}
}
The purpose for building this was because I wanted to use jQuery's post function to do some JS work with a form before it was submitted, but also wanted to redirect alongside the POST request, like a natural form.
javascript jquery ajax
add a comment |
Today I just completed a personal POST function that emulates jQuery's using $.ajax, but also implementing a possible redirect. I just finished up and it looks like it is functional, but since this is something I want to keep long term and integrate in many projects, I want to make sure it is as functional as possible.
function postR(url, params, redir = false, callback = null) {
if(redir){
var form = document.createElement('form');
form.method = 'post';
form.action = url;
for (var key in params) {
var input = document.createElement('input');
input.type = 'hidden';
input.name = key;
input.value = params[key];
form.appendChild(input);
}
document.body.appendChild(form);
form.submit();
}else{
if(callback && typeof(callback) === "function"){
$.ajax({
type: "POST",
url: url,
data: params,
success: function(data){
callback(data)
}
});
}else{
$.ajax({
type: "POST",
url: url,
data: params
});
}
}
}
The purpose for building this was because I wanted to use jQuery's post function to do some JS work with a form before it was submitted, but also wanted to redirect alongside the POST request, like a natural form.
javascript jquery ajax
I have rolled back your last edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see what you may and may not do after receiving answers.
– Heslacher
2 days ago
add a comment |
Today I just completed a personal POST function that emulates jQuery's using $.ajax, but also implementing a possible redirect. I just finished up and it looks like it is functional, but since this is something I want to keep long term and integrate in many projects, I want to make sure it is as functional as possible.
function postR(url, params, redir = false, callback = null) {
if(redir){
var form = document.createElement('form');
form.method = 'post';
form.action = url;
for (var key in params) {
var input = document.createElement('input');
input.type = 'hidden';
input.name = key;
input.value = params[key];
form.appendChild(input);
}
document.body.appendChild(form);
form.submit();
}else{
if(callback && typeof(callback) === "function"){
$.ajax({
type: "POST",
url: url,
data: params,
success: function(data){
callback(data)
}
});
}else{
$.ajax({
type: "POST",
url: url,
data: params
});
}
}
}
The purpose for building this was because I wanted to use jQuery's post function to do some JS work with a form before it was submitted, but also wanted to redirect alongside the POST request, like a natural form.
javascript jquery ajax
Today I just completed a personal POST function that emulates jQuery's using $.ajax, but also implementing a possible redirect. I just finished up and it looks like it is functional, but since this is something I want to keep long term and integrate in many projects, I want to make sure it is as functional as possible.
function postR(url, params, redir = false, callback = null) {
if(redir){
var form = document.createElement('form');
form.method = 'post';
form.action = url;
for (var key in params) {
var input = document.createElement('input');
input.type = 'hidden';
input.name = key;
input.value = params[key];
form.appendChild(input);
}
document.body.appendChild(form);
form.submit();
}else{
if(callback && typeof(callback) === "function"){
$.ajax({
type: "POST",
url: url,
data: params,
success: function(data){
callback(data)
}
});
}else{
$.ajax({
type: "POST",
url: url,
data: params
});
}
}
}
The purpose for building this was because I wanted to use jQuery's post function to do some JS work with a form before it was submitted, but also wanted to redirect alongside the POST request, like a natural form.
javascript jquery ajax
javascript jquery ajax
edited 2 days ago
200_success
128k15152414
128k15152414
asked 2 days ago
NebulaCodingNebulaCoding
284
284
I have rolled back your last edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see what you may and may not do after receiving answers.
– Heslacher
2 days ago
add a comment |
I have rolled back your last edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see what you may and may not do after receiving answers.
– Heslacher
2 days ago
I have rolled back your last edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see what you may and may not do after receiving answers.
– Heslacher
2 days ago
I have rolled back your last edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see what you may and may not do after receiving answers.
– Heslacher
2 days ago
add a comment |
4 Answers
4
active
oldest
votes
Your XMLHttpRequest
example looks good, as well as the redirection part. However, to avoid confusion and improve readability, I would divide it into two different functions.
1) Overwriting $.post
is not an easy task as it may seem, but as a basic example you can use something similar to the following, which supports error
and success
callbacks:
/**
* Send a POST request
* @param {String} url
* @param {Object} params
* @param {Function} success
* @param {Function} error
* @returns {XMLHttpRequest}
*/
function post(url, params, success, error) {
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
success && success(xhr.responseText);
} else {
error && error(xhr.responseText);
}
}
};
let formData = new FormData();
for (let p in params) {
formData.append(p, params[p]);
}
xhr.open('POST', url);
xhr.send(formData);
return xhr;
}
2) As I mentioned, the redirection part from your function is good. However, you have an additional option to simulate the redirection. The idea is to load HTML via a XHR request and use it to replace the current document.
/**
* Simulate a redirection
* @param {String} url
* @param {Object} params
* @returns {XMLHttpRequest}
*/
function postR(url, params) {
let success = error = function (data) {
history.pushState('', '', url);
document.open().write(data);
document.close();
};
return post(url, params, success, error);
}
Got it. I do have some questions though, like why are we returning xhr at the end? Usually I call the function on its own, and not setting it equal to anything. Would this impact it at all, or is it just additional functionality?
– NebulaCoding
2 days ago
@NebulaCoding You can safely remove it, since it does not affect anything. On the other hand, it does not interfere with anything, but sometimes it may seem useful. For example, you can get all HTTP headers in this way:var xhr=post('?',{},function(){console.log(xhr.getAllResponseHeaders())});
(or modify the function and pass thexhr
object to the callbacks). By the way, the jQuery always returns thejqXHR
object as result of$.post
,$.get
, or$.ajax
.
– Victor
2 days ago
Ah, see I didn't know jQuery did that. I figured it would be fine, but just wanted to make sure.
– NebulaCoding
2 days ago
add a comment |
I would:
- Use a FormData instead of creating a form element.
- Give it a name better than "postR", like... simply "post"?
- Add an error handler to the $.ajax call
- Unify both $.ajax calls
Pseudo code (Not tested):
function post(url, params, redir = false, callback = null) {
var formData = new FormData();
for (var key in params) {
formData.append(key, value);
}
$.ajax({
type: "POST",
url: url,
data: formData,
success: function(data) {
typeof(callback) === "function" && callback(data);
redir && window.location.reload();
}
});
}
New contributor
I have it as postR to signify post Redirect, but that's just for me, not worried about keeping it lol
– NebulaCoding
2 days ago
1
Looking at the redirect, does window.location.reload bring you to the destination of the POST request? To me it looks like it will just reload that page after sending the data, where I am trying to redirect WITH the POST data.
– NebulaCoding
2 days ago
@guest271314 Yes - Fixed
– Theone Lucas
2 days ago
@NebulaCoding Yes, it will reload, but only after the POST was sent successfully. It have the same effects, try it.
– Theone Lucas
2 days ago
Understood. If for whatever reason I couldn't achieve my desired functionality with my other setup, I would use this.
– NebulaCoding
2 days ago
add a comment |
I have incorporated some of the things suggested, but I still don't understand exactly how I should do error reporting. I got rid of the second If..Else statement, and also swapped to not use .ajax but XmlHttpRequest(). I did swap to using FormData as well.
function postR(url, params, redir = false, callback = null) {
if(redir){
var form = document.createElement('form');
form.method = 'post';
form.action = url;
for (var key in params) {
var input = document.createElement('input');
input.type = 'hidden';
input.name = key;
input.value = params[key];
form.appendChild(input);
}
document.body.appendChild(form);
form.submit();
}else{
let xhttp, formData;
xhttp = new XMLHttpRequest();
formData = new FormData();
xhttp.onreadystatechange = function(){
if(this.readyState == 4){
if(this.status == 200){
if(callback){
callback(this.responseText);
}else{
console.log(`POST succeeded`);
}
}else{
console.log(`Some error has occurred, error status: ${this.status}, text: ${this.statusText}`);
}
}
};
xhttp.open('POST', url, true);
for(let key in params){
if(params.hasOwnProperty(key)) {
formData.append(key, params[key]);
}
}
xhttp.send(formData);
}
}
add a comment |
It's really not a good idea to "simulate" a page change by messing with the history like is shown in the chosen answer. It might work for one case but as a general function it is a bad idea. I would however employ a helper function for generating DOM elements, and I would use fetch instead of xhr.
function post(url, params, redir = false, callback = null) {
if (redir) {
const mkele = (tag, props, parent) => {
var ele = document.createElement(tag);
for(prop in props) ele.setAttribute(prop, props[prop]);
parent.appendChild(ele);
return ele;
};
const form = mkele('form', {method:"POST", action:url}, document.body);
for (let k in params) mkele('input', {name:k, value:params[k], type:'hidden'}, form);
form.submit();
} else {
const fd = new FormData();
for (let param in params) fd.append(param, params[param])
fetch(url, {method:"POST", body:fd}).then(callback);
}
}
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
return StackExchange.using("mathjaxEditing", function () {
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
});
});
}, "mathjax-editing");
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "196"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f211036%2freplacement-function-for-jquery-post%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
4 Answers
4
active
oldest
votes
4 Answers
4
active
oldest
votes
active
oldest
votes
active
oldest
votes
Your XMLHttpRequest
example looks good, as well as the redirection part. However, to avoid confusion and improve readability, I would divide it into two different functions.
1) Overwriting $.post
is not an easy task as it may seem, but as a basic example you can use something similar to the following, which supports error
and success
callbacks:
/**
* Send a POST request
* @param {String} url
* @param {Object} params
* @param {Function} success
* @param {Function} error
* @returns {XMLHttpRequest}
*/
function post(url, params, success, error) {
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
success && success(xhr.responseText);
} else {
error && error(xhr.responseText);
}
}
};
let formData = new FormData();
for (let p in params) {
formData.append(p, params[p]);
}
xhr.open('POST', url);
xhr.send(formData);
return xhr;
}
2) As I mentioned, the redirection part from your function is good. However, you have an additional option to simulate the redirection. The idea is to load HTML via a XHR request and use it to replace the current document.
/**
* Simulate a redirection
* @param {String} url
* @param {Object} params
* @returns {XMLHttpRequest}
*/
function postR(url, params) {
let success = error = function (data) {
history.pushState('', '', url);
document.open().write(data);
document.close();
};
return post(url, params, success, error);
}
Got it. I do have some questions though, like why are we returning xhr at the end? Usually I call the function on its own, and not setting it equal to anything. Would this impact it at all, or is it just additional functionality?
– NebulaCoding
2 days ago
@NebulaCoding You can safely remove it, since it does not affect anything. On the other hand, it does not interfere with anything, but sometimes it may seem useful. For example, you can get all HTTP headers in this way:var xhr=post('?',{},function(){console.log(xhr.getAllResponseHeaders())});
(or modify the function and pass thexhr
object to the callbacks). By the way, the jQuery always returns thejqXHR
object as result of$.post
,$.get
, or$.ajax
.
– Victor
2 days ago
Ah, see I didn't know jQuery did that. I figured it would be fine, but just wanted to make sure.
– NebulaCoding
2 days ago
add a comment |
Your XMLHttpRequest
example looks good, as well as the redirection part. However, to avoid confusion and improve readability, I would divide it into two different functions.
1) Overwriting $.post
is not an easy task as it may seem, but as a basic example you can use something similar to the following, which supports error
and success
callbacks:
/**
* Send a POST request
* @param {String} url
* @param {Object} params
* @param {Function} success
* @param {Function} error
* @returns {XMLHttpRequest}
*/
function post(url, params, success, error) {
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
success && success(xhr.responseText);
} else {
error && error(xhr.responseText);
}
}
};
let formData = new FormData();
for (let p in params) {
formData.append(p, params[p]);
}
xhr.open('POST', url);
xhr.send(formData);
return xhr;
}
2) As I mentioned, the redirection part from your function is good. However, you have an additional option to simulate the redirection. The idea is to load HTML via a XHR request and use it to replace the current document.
/**
* Simulate a redirection
* @param {String} url
* @param {Object} params
* @returns {XMLHttpRequest}
*/
function postR(url, params) {
let success = error = function (data) {
history.pushState('', '', url);
document.open().write(data);
document.close();
};
return post(url, params, success, error);
}
Got it. I do have some questions though, like why are we returning xhr at the end? Usually I call the function on its own, and not setting it equal to anything. Would this impact it at all, or is it just additional functionality?
– NebulaCoding
2 days ago
@NebulaCoding You can safely remove it, since it does not affect anything. On the other hand, it does not interfere with anything, but sometimes it may seem useful. For example, you can get all HTTP headers in this way:var xhr=post('?',{},function(){console.log(xhr.getAllResponseHeaders())});
(or modify the function and pass thexhr
object to the callbacks). By the way, the jQuery always returns thejqXHR
object as result of$.post
,$.get
, or$.ajax
.
– Victor
2 days ago
Ah, see I didn't know jQuery did that. I figured it would be fine, but just wanted to make sure.
– NebulaCoding
2 days ago
add a comment |
Your XMLHttpRequest
example looks good, as well as the redirection part. However, to avoid confusion and improve readability, I would divide it into two different functions.
1) Overwriting $.post
is not an easy task as it may seem, but as a basic example you can use something similar to the following, which supports error
and success
callbacks:
/**
* Send a POST request
* @param {String} url
* @param {Object} params
* @param {Function} success
* @param {Function} error
* @returns {XMLHttpRequest}
*/
function post(url, params, success, error) {
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
success && success(xhr.responseText);
} else {
error && error(xhr.responseText);
}
}
};
let formData = new FormData();
for (let p in params) {
formData.append(p, params[p]);
}
xhr.open('POST', url);
xhr.send(formData);
return xhr;
}
2) As I mentioned, the redirection part from your function is good. However, you have an additional option to simulate the redirection. The idea is to load HTML via a XHR request and use it to replace the current document.
/**
* Simulate a redirection
* @param {String} url
* @param {Object} params
* @returns {XMLHttpRequest}
*/
function postR(url, params) {
let success = error = function (data) {
history.pushState('', '', url);
document.open().write(data);
document.close();
};
return post(url, params, success, error);
}
Your XMLHttpRequest
example looks good, as well as the redirection part. However, to avoid confusion and improve readability, I would divide it into two different functions.
1) Overwriting $.post
is not an easy task as it may seem, but as a basic example you can use something similar to the following, which supports error
and success
callbacks:
/**
* Send a POST request
* @param {String} url
* @param {Object} params
* @param {Function} success
* @param {Function} error
* @returns {XMLHttpRequest}
*/
function post(url, params, success, error) {
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
success && success(xhr.responseText);
} else {
error && error(xhr.responseText);
}
}
};
let formData = new FormData();
for (let p in params) {
formData.append(p, params[p]);
}
xhr.open('POST', url);
xhr.send(formData);
return xhr;
}
2) As I mentioned, the redirection part from your function is good. However, you have an additional option to simulate the redirection. The idea is to load HTML via a XHR request and use it to replace the current document.
/**
* Simulate a redirection
* @param {String} url
* @param {Object} params
* @returns {XMLHttpRequest}
*/
function postR(url, params) {
let success = error = function (data) {
history.pushState('', '', url);
document.open().write(data);
document.close();
};
return post(url, params, success, error);
}
answered 2 days ago
VictorVictor
2776
2776
Got it. I do have some questions though, like why are we returning xhr at the end? Usually I call the function on its own, and not setting it equal to anything. Would this impact it at all, or is it just additional functionality?
– NebulaCoding
2 days ago
@NebulaCoding You can safely remove it, since it does not affect anything. On the other hand, it does not interfere with anything, but sometimes it may seem useful. For example, you can get all HTTP headers in this way:var xhr=post('?',{},function(){console.log(xhr.getAllResponseHeaders())});
(or modify the function and pass thexhr
object to the callbacks). By the way, the jQuery always returns thejqXHR
object as result of$.post
,$.get
, or$.ajax
.
– Victor
2 days ago
Ah, see I didn't know jQuery did that. I figured it would be fine, but just wanted to make sure.
– NebulaCoding
2 days ago
add a comment |
Got it. I do have some questions though, like why are we returning xhr at the end? Usually I call the function on its own, and not setting it equal to anything. Would this impact it at all, or is it just additional functionality?
– NebulaCoding
2 days ago
@NebulaCoding You can safely remove it, since it does not affect anything. On the other hand, it does not interfere with anything, but sometimes it may seem useful. For example, you can get all HTTP headers in this way:var xhr=post('?',{},function(){console.log(xhr.getAllResponseHeaders())});
(or modify the function and pass thexhr
object to the callbacks). By the way, the jQuery always returns thejqXHR
object as result of$.post
,$.get
, or$.ajax
.
– Victor
2 days ago
Ah, see I didn't know jQuery did that. I figured it would be fine, but just wanted to make sure.
– NebulaCoding
2 days ago
Got it. I do have some questions though, like why are we returning xhr at the end? Usually I call the function on its own, and not setting it equal to anything. Would this impact it at all, or is it just additional functionality?
– NebulaCoding
2 days ago
Got it. I do have some questions though, like why are we returning xhr at the end? Usually I call the function on its own, and not setting it equal to anything. Would this impact it at all, or is it just additional functionality?
– NebulaCoding
2 days ago
@NebulaCoding You can safely remove it, since it does not affect anything. On the other hand, it does not interfere with anything, but sometimes it may seem useful. For example, you can get all HTTP headers in this way:
var xhr=post('?',{},function(){console.log(xhr.getAllResponseHeaders())});
(or modify the function and pass the xhr
object to the callbacks). By the way, the jQuery always returns the jqXHR
object as result of $.post
, $.get
, or $.ajax
.– Victor
2 days ago
@NebulaCoding You can safely remove it, since it does not affect anything. On the other hand, it does not interfere with anything, but sometimes it may seem useful. For example, you can get all HTTP headers in this way:
var xhr=post('?',{},function(){console.log(xhr.getAllResponseHeaders())});
(or modify the function and pass the xhr
object to the callbacks). By the way, the jQuery always returns the jqXHR
object as result of $.post
, $.get
, or $.ajax
.– Victor
2 days ago
Ah, see I didn't know jQuery did that. I figured it would be fine, but just wanted to make sure.
– NebulaCoding
2 days ago
Ah, see I didn't know jQuery did that. I figured it would be fine, but just wanted to make sure.
– NebulaCoding
2 days ago
add a comment |
I would:
- Use a FormData instead of creating a form element.
- Give it a name better than "postR", like... simply "post"?
- Add an error handler to the $.ajax call
- Unify both $.ajax calls
Pseudo code (Not tested):
function post(url, params, redir = false, callback = null) {
var formData = new FormData();
for (var key in params) {
formData.append(key, value);
}
$.ajax({
type: "POST",
url: url,
data: formData,
success: function(data) {
typeof(callback) === "function" && callback(data);
redir && window.location.reload();
}
});
}
New contributor
I have it as postR to signify post Redirect, but that's just for me, not worried about keeping it lol
– NebulaCoding
2 days ago
1
Looking at the redirect, does window.location.reload bring you to the destination of the POST request? To me it looks like it will just reload that page after sending the data, where I am trying to redirect WITH the POST data.
– NebulaCoding
2 days ago
@guest271314 Yes - Fixed
– Theone Lucas
2 days ago
@NebulaCoding Yes, it will reload, but only after the POST was sent successfully. It have the same effects, try it.
– Theone Lucas
2 days ago
Understood. If for whatever reason I couldn't achieve my desired functionality with my other setup, I would use this.
– NebulaCoding
2 days ago
add a comment |
I would:
- Use a FormData instead of creating a form element.
- Give it a name better than "postR", like... simply "post"?
- Add an error handler to the $.ajax call
- Unify both $.ajax calls
Pseudo code (Not tested):
function post(url, params, redir = false, callback = null) {
var formData = new FormData();
for (var key in params) {
formData.append(key, value);
}
$.ajax({
type: "POST",
url: url,
data: formData,
success: function(data) {
typeof(callback) === "function" && callback(data);
redir && window.location.reload();
}
});
}
New contributor
I have it as postR to signify post Redirect, but that's just for me, not worried about keeping it lol
– NebulaCoding
2 days ago
1
Looking at the redirect, does window.location.reload bring you to the destination of the POST request? To me it looks like it will just reload that page after sending the data, where I am trying to redirect WITH the POST data.
– NebulaCoding
2 days ago
@guest271314 Yes - Fixed
– Theone Lucas
2 days ago
@NebulaCoding Yes, it will reload, but only after the POST was sent successfully. It have the same effects, try it.
– Theone Lucas
2 days ago
Understood. If for whatever reason I couldn't achieve my desired functionality with my other setup, I would use this.
– NebulaCoding
2 days ago
add a comment |
I would:
- Use a FormData instead of creating a form element.
- Give it a name better than "postR", like... simply "post"?
- Add an error handler to the $.ajax call
- Unify both $.ajax calls
Pseudo code (Not tested):
function post(url, params, redir = false, callback = null) {
var formData = new FormData();
for (var key in params) {
formData.append(key, value);
}
$.ajax({
type: "POST",
url: url,
data: formData,
success: function(data) {
typeof(callback) === "function" && callback(data);
redir && window.location.reload();
}
});
}
New contributor
I would:
- Use a FormData instead of creating a form element.
- Give it a name better than "postR", like... simply "post"?
- Add an error handler to the $.ajax call
- Unify both $.ajax calls
Pseudo code (Not tested):
function post(url, params, redir = false, callback = null) {
var formData = new FormData();
for (var key in params) {
formData.append(key, value);
}
$.ajax({
type: "POST",
url: url,
data: formData,
success: function(data) {
typeof(callback) === "function" && callback(data);
redir && window.location.reload();
}
});
}
New contributor
edited 2 days ago
New contributor
answered 2 days ago
Theone LucasTheone Lucas
313
313
New contributor
New contributor
I have it as postR to signify post Redirect, but that's just for me, not worried about keeping it lol
– NebulaCoding
2 days ago
1
Looking at the redirect, does window.location.reload bring you to the destination of the POST request? To me it looks like it will just reload that page after sending the data, where I am trying to redirect WITH the POST data.
– NebulaCoding
2 days ago
@guest271314 Yes - Fixed
– Theone Lucas
2 days ago
@NebulaCoding Yes, it will reload, but only after the POST was sent successfully. It have the same effects, try it.
– Theone Lucas
2 days ago
Understood. If for whatever reason I couldn't achieve my desired functionality with my other setup, I would use this.
– NebulaCoding
2 days ago
add a comment |
I have it as postR to signify post Redirect, but that's just for me, not worried about keeping it lol
– NebulaCoding
2 days ago
1
Looking at the redirect, does window.location.reload bring you to the destination of the POST request? To me it looks like it will just reload that page after sending the data, where I am trying to redirect WITH the POST data.
– NebulaCoding
2 days ago
@guest271314 Yes - Fixed
– Theone Lucas
2 days ago
@NebulaCoding Yes, it will reload, but only after the POST was sent successfully. It have the same effects, try it.
– Theone Lucas
2 days ago
Understood. If for whatever reason I couldn't achieve my desired functionality with my other setup, I would use this.
– NebulaCoding
2 days ago
I have it as postR to signify post Redirect, but that's just for me, not worried about keeping it lol
– NebulaCoding
2 days ago
I have it as postR to signify post Redirect, but that's just for me, not worried about keeping it lol
– NebulaCoding
2 days ago
1
1
Looking at the redirect, does window.location.reload bring you to the destination of the POST request? To me it looks like it will just reload that page after sending the data, where I am trying to redirect WITH the POST data.
– NebulaCoding
2 days ago
Looking at the redirect, does window.location.reload bring you to the destination of the POST request? To me it looks like it will just reload that page after sending the data, where I am trying to redirect WITH the POST data.
– NebulaCoding
2 days ago
@guest271314 Yes - Fixed
– Theone Lucas
2 days ago
@guest271314 Yes - Fixed
– Theone Lucas
2 days ago
@NebulaCoding Yes, it will reload, but only after the POST was sent successfully. It have the same effects, try it.
– Theone Lucas
2 days ago
@NebulaCoding Yes, it will reload, but only after the POST was sent successfully. It have the same effects, try it.
– Theone Lucas
2 days ago
Understood. If for whatever reason I couldn't achieve my desired functionality with my other setup, I would use this.
– NebulaCoding
2 days ago
Understood. If for whatever reason I couldn't achieve my desired functionality with my other setup, I would use this.
– NebulaCoding
2 days ago
add a comment |
I have incorporated some of the things suggested, but I still don't understand exactly how I should do error reporting. I got rid of the second If..Else statement, and also swapped to not use .ajax but XmlHttpRequest(). I did swap to using FormData as well.
function postR(url, params, redir = false, callback = null) {
if(redir){
var form = document.createElement('form');
form.method = 'post';
form.action = url;
for (var key in params) {
var input = document.createElement('input');
input.type = 'hidden';
input.name = key;
input.value = params[key];
form.appendChild(input);
}
document.body.appendChild(form);
form.submit();
}else{
let xhttp, formData;
xhttp = new XMLHttpRequest();
formData = new FormData();
xhttp.onreadystatechange = function(){
if(this.readyState == 4){
if(this.status == 200){
if(callback){
callback(this.responseText);
}else{
console.log(`POST succeeded`);
}
}else{
console.log(`Some error has occurred, error status: ${this.status}, text: ${this.statusText}`);
}
}
};
xhttp.open('POST', url, true);
for(let key in params){
if(params.hasOwnProperty(key)) {
formData.append(key, params[key]);
}
}
xhttp.send(formData);
}
}
add a comment |
I have incorporated some of the things suggested, but I still don't understand exactly how I should do error reporting. I got rid of the second If..Else statement, and also swapped to not use .ajax but XmlHttpRequest(). I did swap to using FormData as well.
function postR(url, params, redir = false, callback = null) {
if(redir){
var form = document.createElement('form');
form.method = 'post';
form.action = url;
for (var key in params) {
var input = document.createElement('input');
input.type = 'hidden';
input.name = key;
input.value = params[key];
form.appendChild(input);
}
document.body.appendChild(form);
form.submit();
}else{
let xhttp, formData;
xhttp = new XMLHttpRequest();
formData = new FormData();
xhttp.onreadystatechange = function(){
if(this.readyState == 4){
if(this.status == 200){
if(callback){
callback(this.responseText);
}else{
console.log(`POST succeeded`);
}
}else{
console.log(`Some error has occurred, error status: ${this.status}, text: ${this.statusText}`);
}
}
};
xhttp.open('POST', url, true);
for(let key in params){
if(params.hasOwnProperty(key)) {
formData.append(key, params[key]);
}
}
xhttp.send(formData);
}
}
add a comment |
I have incorporated some of the things suggested, but I still don't understand exactly how I should do error reporting. I got rid of the second If..Else statement, and also swapped to not use .ajax but XmlHttpRequest(). I did swap to using FormData as well.
function postR(url, params, redir = false, callback = null) {
if(redir){
var form = document.createElement('form');
form.method = 'post';
form.action = url;
for (var key in params) {
var input = document.createElement('input');
input.type = 'hidden';
input.name = key;
input.value = params[key];
form.appendChild(input);
}
document.body.appendChild(form);
form.submit();
}else{
let xhttp, formData;
xhttp = new XMLHttpRequest();
formData = new FormData();
xhttp.onreadystatechange = function(){
if(this.readyState == 4){
if(this.status == 200){
if(callback){
callback(this.responseText);
}else{
console.log(`POST succeeded`);
}
}else{
console.log(`Some error has occurred, error status: ${this.status}, text: ${this.statusText}`);
}
}
};
xhttp.open('POST', url, true);
for(let key in params){
if(params.hasOwnProperty(key)) {
formData.append(key, params[key]);
}
}
xhttp.send(formData);
}
}
I have incorporated some of the things suggested, but I still don't understand exactly how I should do error reporting. I got rid of the second If..Else statement, and also swapped to not use .ajax but XmlHttpRequest(). I did swap to using FormData as well.
function postR(url, params, redir = false, callback = null) {
if(redir){
var form = document.createElement('form');
form.method = 'post';
form.action = url;
for (var key in params) {
var input = document.createElement('input');
input.type = 'hidden';
input.name = key;
input.value = params[key];
form.appendChild(input);
}
document.body.appendChild(form);
form.submit();
}else{
let xhttp, formData;
xhttp = new XMLHttpRequest();
formData = new FormData();
xhttp.onreadystatechange = function(){
if(this.readyState == 4){
if(this.status == 200){
if(callback){
callback(this.responseText);
}else{
console.log(`POST succeeded`);
}
}else{
console.log(`Some error has occurred, error status: ${this.status}, text: ${this.statusText}`);
}
}
};
xhttp.open('POST', url, true);
for(let key in params){
if(params.hasOwnProperty(key)) {
formData.append(key, params[key]);
}
}
xhttp.send(formData);
}
}
answered 2 days ago
NebulaCodingNebulaCoding
284
284
add a comment |
add a comment |
It's really not a good idea to "simulate" a page change by messing with the history like is shown in the chosen answer. It might work for one case but as a general function it is a bad idea. I would however employ a helper function for generating DOM elements, and I would use fetch instead of xhr.
function post(url, params, redir = false, callback = null) {
if (redir) {
const mkele = (tag, props, parent) => {
var ele = document.createElement(tag);
for(prop in props) ele.setAttribute(prop, props[prop]);
parent.appendChild(ele);
return ele;
};
const form = mkele('form', {method:"POST", action:url}, document.body);
for (let k in params) mkele('input', {name:k, value:params[k], type:'hidden'}, form);
form.submit();
} else {
const fd = new FormData();
for (let param in params) fd.append(param, params[param])
fetch(url, {method:"POST", body:fd}).then(callback);
}
}
add a comment |
It's really not a good idea to "simulate" a page change by messing with the history like is shown in the chosen answer. It might work for one case but as a general function it is a bad idea. I would however employ a helper function for generating DOM elements, and I would use fetch instead of xhr.
function post(url, params, redir = false, callback = null) {
if (redir) {
const mkele = (tag, props, parent) => {
var ele = document.createElement(tag);
for(prop in props) ele.setAttribute(prop, props[prop]);
parent.appendChild(ele);
return ele;
};
const form = mkele('form', {method:"POST", action:url}, document.body);
for (let k in params) mkele('input', {name:k, value:params[k], type:'hidden'}, form);
form.submit();
} else {
const fd = new FormData();
for (let param in params) fd.append(param, params[param])
fetch(url, {method:"POST", body:fd}).then(callback);
}
}
add a comment |
It's really not a good idea to "simulate" a page change by messing with the history like is shown in the chosen answer. It might work for one case but as a general function it is a bad idea. I would however employ a helper function for generating DOM elements, and I would use fetch instead of xhr.
function post(url, params, redir = false, callback = null) {
if (redir) {
const mkele = (tag, props, parent) => {
var ele = document.createElement(tag);
for(prop in props) ele.setAttribute(prop, props[prop]);
parent.appendChild(ele);
return ele;
};
const form = mkele('form', {method:"POST", action:url}, document.body);
for (let k in params) mkele('input', {name:k, value:params[k], type:'hidden'}, form);
form.submit();
} else {
const fd = new FormData();
for (let param in params) fd.append(param, params[param])
fetch(url, {method:"POST", body:fd}).then(callback);
}
}
It's really not a good idea to "simulate" a page change by messing with the history like is shown in the chosen answer. It might work for one case but as a general function it is a bad idea. I would however employ a helper function for generating DOM elements, and I would use fetch instead of xhr.
function post(url, params, redir = false, callback = null) {
if (redir) {
const mkele = (tag, props, parent) => {
var ele = document.createElement(tag);
for(prop in props) ele.setAttribute(prop, props[prop]);
parent.appendChild(ele);
return ele;
};
const form = mkele('form', {method:"POST", action:url}, document.body);
for (let k in params) mkele('input', {name:k, value:params[k], type:'hidden'}, form);
form.submit();
} else {
const fd = new FormData();
for (let param in params) fd.append(param, params[param])
fetch(url, {method:"POST", body:fd}).then(callback);
}
}
function post(url, params, redir = false, callback = null) {
if (redir) {
const mkele = (tag, props, parent) => {
var ele = document.createElement(tag);
for(prop in props) ele.setAttribute(prop, props[prop]);
parent.appendChild(ele);
return ele;
};
const form = mkele('form', {method:"POST", action:url}, document.body);
for (let k in params) mkele('input', {name:k, value:params[k], type:'hidden'}, form);
form.submit();
} else {
const fd = new FormData();
for (let param in params) fd.append(param, params[param])
fetch(url, {method:"POST", body:fd}).then(callback);
}
}
function post(url, params, redir = false, callback = null) {
if (redir) {
const mkele = (tag, props, parent) => {
var ele = document.createElement(tag);
for(prop in props) ele.setAttribute(prop, props[prop]);
parent.appendChild(ele);
return ele;
};
const form = mkele('form', {method:"POST", action:url}, document.body);
for (let k in params) mkele('input', {name:k, value:params[k], type:'hidden'}, form);
form.submit();
} else {
const fd = new FormData();
for (let param in params) fd.append(param, params[param])
fetch(url, {method:"POST", body:fd}).then(callback);
}
}
answered yesterday
iwrestledabearonceiwrestledabearonce
2,022513
2,022513
add a comment |
add a comment |
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f211036%2freplacement-function-for-jquery-post%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
I have rolled back your last edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see what you may and may not do after receiving answers.
– Heslacher
2 days ago