Created
September 6, 2012 17:31
-
-
Save tom--/3658792 to your computer and use it in GitHub Desktop.
Unobtrusive ajax link
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <html> | |
| <head></head> | |
| <body> | |
| <p><a id="theajaxlink" href="xhrhandler.php?p=1&q=2">text</a></p> | |
| <script type="text/javascript"> | |
| (function () { | |
| 'use strict'; | |
| var clickhandler = function (e) { | |
| var $that = $(this); | |
| e.preventDefault(); | |
| $.ajax({ | |
| url: $that.attr('href'), | |
| data: {'__from': '__xhr'}, | |
| success: function () { | |
| // whatever | |
| } | |
| }); | |
| return false; | |
| }; | |
| jQuery(function ($) { | |
| $('#theajaxlink').on('click', clickhandler); | |
| }); | |
| }()); | |
| </script> | |
| </body> | |
| </html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| $ajax = (isset($_GET['__from']) && $_GET['__from'] === '__xhr') | |
| || (isset($_SERVER['HTTP_X_REQUESTED_WITH']) | |
| && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest'); | |
| // 1. Do whatever work is handler script is supposed to do. | |
| if ($ajax) { | |
| // 2. Output HTTP body content, if any. | |
| } else { | |
| // 3. Redirect to 'thepage.html'. | |
| // If @2. would have had any body output then it MUST be reflected in thepage.html | |
| // when the client requests it after redirect @3. <-- is a requirement on thepage.html. | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment