Hi,
I have a form with file uploads and because Turbo is using Fetch behind the scene, it isn’t possible to monitor upload progress. What I do instead is I catch the form submit event, cancel it and do it by AJAX (using Axios but doesn’t really matter) and then when I have the response, I tell Turbo to load it.
To make it very simple here is a code snippet
Axios.post(...).then((response) => {
Turbo.visit(response.request.responseURL, {
action: "replace",
response: { statusCode: 200, redirected: true, responseHTML: response.data }
});
}).catch((response) => {
if (response.code === 422) {
Turbo.visit(location.href, {
action: "replace",
response: { statusCode: 422, redirected: false, responseHTML: response.data }
});
}
});
Scenario HTTP 200
It doesn’t care I provide the HTML response, Turbo will make a subsequent GET to the URL and load that response. It’s not that bad because in the end the page load anyway… but just wanted to point it out
Scenario HTTP 422
It loads the given HTML response without making a subsequent call to the URL. However, for some reasons, all the Javascript is reloaded generating the error shown below
My questions are
- Why is it inconsistent (i.e ignoring HTML response in case of a 200)
- Why does it reloads all my JS? When I click an anchor link
<a href="...">
it doesn’t. How can I make my Turbo.visit behave the same?
Workaround
const { body } = (new DOMParser()).parseFromString(response.data, 'text/html');
document.body.replaceWith(body);