Frank DENIS random thoughts.

Submitting a form without changing the window's content

There’s an old HTTP feature, that is fully documented and implemented by every popular browser, but that remains unknown to most webmasters: HTTP Status 204 aka “No Content”.

HTTP Status 204 tells the browser to keep the previous content of the window.

For instance here’s a very basic form, that submits to nc2.php:


<html>
<body>
<form action="nc2.php" method="post">
<div>
<input type="text" name="yo" value="" />
<input type="submit" value="go !" />
</div>
</form>
</body>
</html>

Now here’s nc2.php:


<?php
header('HTTP/1.1 204 No Content');
?>

When the form is submitted, nothing disappears. nc2.php is properly called but the HTTP Status 204 tells the browser to avoid changing the window’s content.

No need for AJAX to process the form data without reloading the page, although the server can’t sent back any data to the client.

However, any other HTTP header can be used in a 204 reponse. For instance, cookies can be set, or redirections can happen.


<?php
header('HTTP/1.1 204 No Content');
... process $_POST[] ...
setcookie('xxx', 'yyy');
header('Location: http://www.example.com');
?>

There are many uses for that trick. I just used for a chat room: messages from users are sent to the server and the page is not reloaded as forms are submitted. It saves some AJAX code.

There’s a funny bug in Safari and Webkit while mixing HTTP Status 204 and Location: headers, by the way. After the redirection, the second site’s favicon.ico icon is assigned to the first site. Hopefully the same mixup doesn’t happen with more critical data, like cookies.