0

We have a widget that has a link that sends the user to a particular page. That link has a couple of parameters, one of which is based on some data entered in the widget. However, if enough data is entered into the widget, that parameter can push the length of the URL past the 2048 character limit, where it ends up being truncated, resulting in a 404 error. I would like to be able to make a link that uses a POST request to open the page in order to get around that limit.

Can anyone tell me how to accomplish that using JavaScript? I've found solutions for C#, solutions that use Angular and solutions that do a submit or all manner of other things; but none of that helps me for my particular situation, which is to send the user to another page with some data that could be too long to fit in a regular URL when he clicks on a link, with the implementation in JavaScript. (AJAX requests are OK if appropriate; we have a couple of different ways to send them at our disposal. Also, the solution has to work with IE, as we're still supporting IE 11.)

RobH
  • 1,607
  • 2
  • 24
  • 44

1 Answers1

0

You can use the fetch API for that, it's pretty easy and supported by all major browser by default except IE. You just need to make an object with all the data you want to sent to the API then stringify that data to the body of the request.

A simple example of the POST request:

fetch('http://localhost:3000/someendpoint', {
  headers: {},
  body: JSON.stringify({ data: 'I am the data that arrives on the server'}),
  method: POST
})
  .then(res => res.json())
  .then(data => console.log('The response from the server ', data))
  .catch(e => console.error(e))

The Fetch API needs to resolve 2 promises!

In the second promise data you can execute whatever you want once the request is successfully completed.

  • Unfortunately, anything that doesn't support IE is out, as we're still supporting IE 11. – RobH Oct 23 '20 at 16:29
  • https://stackoverflow.com/questions/56137702/fetch-in-internet-explorer it appears if you transpile your project using Babel you could be able to achieve it. It's not that difficult to transpile a javascript file. https://medium.com/@ramez.aijaz/transpile-typescript-to-es5-using-babel-and-webpack-f3b72a157399 – Maarten Coppens Oct 23 '20 at 18:37
  • I'm afraid that using Babel to get Fetch to work on IE is out of the question, too. We're running on a tight deadline and don't have enough resources on our team to start futzing around with transpilers for our JavaScript code. Also, the Javascript that would need to be transpiled is in a .phtml file. We really don't want to have to start ripping our files apart for the sake of getting one thing to work on an old browser that we may not be supporting for much longer. However, we are still supporting IE for now, so whatever solution I use has to work on it. – RobH Oct 27 '20 at 00:34