This is related to my XYZ app to write comments.
I found a much neater way to submit the request using forms:
function post() {
se_url='https://api.stackexchange.com/2.3/posts/'+se_postId.value+'/comments/add';
se_form.action=se_url;
se_form.submit();
}
<form id="se_form" onsubmit="post();" method="post">
<input type="text" id="se_access_token" name="access_token" value="">
<label for="se_access_token">Access token</label>
<br>
<input type="text" id="se_postId" name="id" value="51812">
<label for="se_postId">Post Id</label>
<br>
<input type="text" maxlength=100 id="se_body" name="body" value="Test comment sent from App xyz">
<label for="se_body">Comment</label>
<input type="hidden" id="se_preview" name="preview" value="false">
<br>
<input type="text" id="se_key" name="key" value="3SgaKR3yq2M1tzN3dNu*Cw((">
<label for="se_preview">App key</label>
<br>
<input type="text" id="se_site" name="site" value="meta">
<label for="se_preview">Site</label>
<input type="hidden" id="se_filter" name="filter" value="default">
<br>
<input type="submit" value="post">
</form>
where the three lines in the post()
function replace this:
inps=se_form.getElementsByTagName('input');
se_postBody='';
for (i in inps)
if (inps[i].id) se_postBody+=inps[i].name+'='+inps[i].value+'&';
se_postBody=se_postBody.slice(0,-1);
xh = new XMLHttpRequest();
xh.open("POST", se_url);
xh.onload=function() {out.textContent=xh.responseText;}
xh.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xh.send(se_postBody);
Unfortunately, I get whizzed off to
but then I have no way to access the response text.
Is there a way around this?
XMLHttpRequest
instead?submit
listener and prevent the default event action. Unfortunately, that will bring you back to square one of using eitherXMLHttpRequest
orfetch
. P.s. Sorry, forgot to send the draftXMLHttpRequest
is still useful when maintaining legacy code or writing one that is compatible with old browsers, so I am mostly asking that part out of curiosity. Fetch equivalent would be something like:fetch(url, { method: "POST", body: <body here, can be an instance of FormData in your case> })
submit
event listener (as it is slightly less verbose thanXMLHttpRequest
) either way to be able to both see the response and not reload the page. Unfortunately, there is little you can do if you want both being able to submit the form and see the response.