Vasily Hall
Vasily Hall

Reputation: 961

HTML form with GET method to PDF file ignores query string

I have this simple web form which has just a single button so the user can open a static PDF file when they click it.

Now that I've updated the PDF file, I updated the query string timestamp cache-busting parameter so they see a new version of the file.

<form action="Path/To/My/PDF Document.pdf?v=1234" target="_blank">
    <button>Get your PDF here!</button>
</form>

Well, the PDF opens up alright, but the querystring is automatically reduced to just the question mark. What opens up is: Path/To/My/PDF Document.pdf?

This shows the original version and not the new one, and I'm wondering what is the matter with this process?

*I know method="GET" is not in my example, but it does the same with or without it.

Upvotes: 0

Views: 202

Answers (1)

Aaron Newton
Aaron Newton

Reputation: 2306

Give this a go:

<form 
 action="Path/To/My/PDF Document.pdf"
 method="GET">
   <input type="hidden" name="v" value="1234" />
    <button>Get your PDF here!</button>
</form>

Key points:

  1. specify the method as GET
  2. provide the query-string parameter as a hidden input, with the name set to the name of the query-string

The reason this works is because of how forms process input data.

Demo: https://jsfiddle.net/1tszbe5o/

Recommended reading for WHY this works: https://developer.mozilla.org/en-US/docs/Learn/Forms/Sending_and_retrieving_form_data

TLDR: when you use the GET method, any form data provided with form inputs will be included in the query-string of the HTTP request resulting from the form action.

Why does it get stripped out in the first place? Because the form data was empty, hence the query-string was empty also ;)

Upvotes: 1

Related Questions