Forms Targeting iframes
The Fetch API and XHR-like “Ajax” requests are the cornerstone of every modern website, but there’s not many options when it comes to legacy browsers.
If all you care about is supporting older IE, you can just use good old ActiveXObject("Microsoft.XMLHTTP")
and it’s ilk, but unfortunately Microsoft in all it’s late 90s wisdom decided to omit that capability from the Unix and Mac OS versions of Internet Explorer (which I actually do think is one of the better old browsers, at least prior to Version 6).
So what can you do instead?
Enter iframes
One of the more esoteric features (at least these days) of HTML forms is the ability to target them at different frames, iframes or even windows.
Here’s a pretty normal looking form, when you submit, it sends a POST to the /search
URL, and the current page will load with the results.
<form method="post" action="/search">
<input name="query">
<input type="submit" value="Search">
</form>
What if we want to see the results without reloading the whole page?
In a modern browser this is where fetch
might step in, but here’s where forms and iframes have a trick up their sleeve:
<form method="post" action="/search" target="search-results">
<input name="query">
<input type="submit" value="Search">
</form>
<iframe name="search-results"></iframe>
Now rather than loading an entirely new page, the response to the form POST gets loaded into the iframe instead.
Pretty neat, and not a single line of Javascript required!
Usually when you have a search interface, it returns a bunch of hyperlinks to other resources. You’ll notice that if you click a result, it will open within the iframe which usually isn’t desirable.
To fix this, change the hyperlinks within the results page to target="_top"
and now when you click links within the iframe, they are loaded in the main browser window instead of in the iframe:
<ul>
<li><a href="/articles/1" target="_top">A nice article</a></li>
<li><a href="/articles/2" target="_top">A great article</a></li>
</ul>