Turbo.visit with HTML response generates error an is inconsistent

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


182653215-335febb2-e665-4826-a251-8fb4ac2963d0

My questions are

  1. Why is it inconsistent (i.e ignoring HTML response in case of a 200)
  2. 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);

Can you provide a github repo example?

1 Like

Sure here you go @tleish

It generates an different error because I used importmaps but I believe it means exactly the same

With importmap : An import map is added after module script load was triggered.

I tried the repo and can’t reproduce the error. In other words, it appears to work correctly in my environment. Have you tried running in incognito mode to ensure a plugin is not causing an issue?

Hi @tleish

Sorry for the late answer, I’m not always present on weekend.

I don’t understand how you’re not getting any errors in your console. I mean, other than the error, it works. I tested two Mac and got the same result.

What are you testing on? I’m using latest Chrome browser on latest Monterrey 12.5

Same (latest chrome on monterey). I see the 422 (unprocessable entity) in the logs, which is expected. I do not see the other errors.

Do you get the same error when running in incognito (with plugins disabled)?

Yes I do. Also it’s not ignoring your response on 200? It’s loading the custom response I give by Javascript?