Skip to content

Instantly share code, notes, and snippets.

@tom--
Created September 6, 2012 17:31
Show Gist options
  • Select an option

  • Save tom--/3658792 to your computer and use it in GitHub Desktop.

Select an option

Save tom--/3658792 to your computer and use it in GitHub Desktop.
Unobtrusive ajax link
<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>
<?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