Answered by:
Explanation for code working in one place and not another

Question
-
User-1699898665 posted
Hi folks...A follow on from my last question. I have the following code which is working fine:
fetch(postURI, { mode: 'cors', method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify(item) }) .then(response => response.json()) .then(body => { if (body != null) { orgId = body.id; window.confirm("Organisation saved"); let redir = ""; if (window.location.port == "") { redir = window.location.protocol + "//" + window.location.hostname + "/TestWebAPIWithJavascript/organisation?OrganisationId=" + orgId; } else { redir = window.location.protocol + "//" + window.location.hostname + ":" + window.location.port + "/TestWebAPIWithJavascript/organisation?OrganisationId=" + orgId; } //Reload this form window.location.replace(redir); //Using replace means that history is overwritten and new records do not get needlessly recreated } else { window.confirm("Organisation : An error occurred whilst saving, please check the console log"); console.log("body is null"); } }) .catch(error => { window.confirm("Organisation : An error occurred whilst saving, please check the console log"); console.error('Unable to add/update item.', error) });
I have highlighted the code the question is about as best I can....it's the code to reoad the page. Ideally I wanted this code here:
function Save() { SaveOrganisation(); //Redirect code was originally here }
Where the SaveOrganisation routine that contains the POSTing fetch statement returns the Id of the Organisation and uses it to reload the page.
But the highlighted code doesn't work in the Save routine. It processes it for sure...I can see it in the debugger. But it only works in the .then() of the fetch statement. Why is this?
Kind regards, Paul
Monday, August 17, 2020 2:51 PM
Answers
-
User753101303 posted
No or I misunderstood your design. I'm just telling that as you triggered the request programmatically, the response to this http request is made available to your JavaScript code and the browser won't ever interfere with that.
When using a "redirect" statement server side, it is just adding a https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location header to the http response to tell to fetch another location.
If done by the browser, the browser will process this response and will then fetch and show the next page.
If done programmatically, the redirect happens and the next page is fetched but this page is still made available as the http response made available to your JavaScript code. The browser won't "hijjack" and decide to process himself the response just because it includes a location header.
Here you are triggering an http request from Ajax but would like the browser to process the response which won't work.
So a common option is to trigger the Ajax call and then tell the browser to fetch another page from the client side once this request is completed. Another option could be to not use Ajax which is less interesting if following the Ajax call you are fetching anyway another page.
Edit: more likely the missing part is that a server side redirect does this by altering the http response sent to the browser? Hopefully it should be clearer now.
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Tuesday, August 18, 2020 6:36 PM
All replies
-
User753101303 posted
Hi,
This is the same for all Ajax requests. As this http request is requested programmaticallty the response is available to JavaScript and the browser will never do anything based on this response even if it includes a redirection, a file download or whatever.
In short either the browser is handling the http request and its response or either you do with JavaScript. There is no "mixed" scenario.
Monday, August 17, 2020 3:30 PM -
User-1699898665 posted
Thanks, but I'm afraid I am none the wiser. I wasn't aware the Submit event of a Form was presciptive about what can happen and when, other than it delivers a request...I understand that in this case the request is being handled by Javascript, but I don't see how the command that is made after the SaveOrganisation function is called somehow becomes part of the HTTP form submit event. In any other language, once SaveOrganisation is done, the next command is processed and if it's invalid in any way we are given an error. I am thinking synchronously here.
Put another way, for me this should be valid:
function DoStuff() {
fetch(uri, {method: 'POST'....etc}).then(process the first response);
fetch(anotherURI, {method: 'POST'....etc}).then(process the second response);
}
By implication you're telling me that this is invalid and everything after the first fetch is ignored...no?
Kind regards, Paul
Tuesday, August 18, 2020 5:14 PM -
User753101303 posted
No or I misunderstood your design. I'm just telling that as you triggered the request programmatically, the response to this http request is made available to your JavaScript code and the browser won't ever interfere with that.
When using a "redirect" statement server side, it is just adding a https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location header to the http response to tell to fetch another location.
If done by the browser, the browser will process this response and will then fetch and show the next page.
If done programmatically, the redirect happens and the next page is fetched but this page is still made available as the http response made available to your JavaScript code. The browser won't "hijjack" and decide to process himself the response just because it includes a location header.
Here you are triggering an http request from Ajax but would like the browser to process the response which won't work.
So a common option is to trigger the Ajax call and then tell the browser to fetch another page from the client side once this request is completed. Another option could be to not use Ajax which is less interesting if following the Ajax call you are fetching anyway another page.
Edit: more likely the missing part is that a server side redirect does this by altering the http response sent to the browser? Hopefully it should be clearer now.
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Tuesday, August 18, 2020 6:36 PM -
User-1699898665 posted
Thanks and I'm sure your explanation will make sense eventually...I only "kind of" get what you're saying...but I just don't see how I am asking the browser to process the response to the fetch once the fetch is completed. The response to the fetch is a redirect in itself, but once that fetch statement is completed (anything after that closing };) I would expect that Javascript would treat the next statement in isolation (whether of a request nature or not)....or to raise an error. I've got no issue with my original code being invalid...fair do's....it's that way the command was processed and simply did nothing that is slightly alarming.
I'll just have to accept what it is for now and do the extremely dull reading up on HTTP that I was hoping to avoid.
Ta very, Paul
Wednesday, August 19, 2020 1:28 PM -
User753101303 posted
For now my understanding is that you wonder why having
function Save() { SaveOrganisation(); // Redirect code here which is done by sending back an additional information in the http response }
on the server side is not enoguh to direct the browser to a new page once the Ajax request is over? The reditect happens but the response is returned to what caused the original http request ie your JavaScript code and so the browser won't use this response to change which document is shown in the current window.
And as shown by your current code you need JavaScript code to tell the browser the document shown by the current window should be loaded from another location.
There is really nothing special compared with other Ajax request. If you fetch an HTML page the browser won't show this page but the HTML response will be available to your code for futher custom processing.
Wednesday, August 19, 2020 3:28 PM