Using the x-requested-with header to include content on demand

Roger Stringer
April 14, 2012
2 min read

I like using the same PHP script for both AJAX and non-AJAX content requests. Using one script just makes everything easier because it's only one file to update/edit and it's one more cache-able request.

One way to try to detect an AJAX request (as opposed to a regular page load) is by using the x-requested-with header when building ajax powered apps..

PHP Code

php
1<?php if($_SERVER['HTTP_X_REQUESTED_WITH']==''){
2    include('header.php');
3}?>
4<blockquote cite="http://ia341030.us.archive.org/1/items/alicesadventures19002gut/19002-h/19002-h.htm">
5    <p>Alice was beginning to get very tired of sitting by her sister
6    on the bank, and of having nothing to do: once or twice she had peeped
7    into the book her sister was reading, but it had no pictures or
8    conversations in it, and where is the use of a book, thought Alice,
9    without pictures or conversations? So she was considering in her own mind,
10    (as well as she could, for the hot day made her feel very sleepy and
11    stupid,) whether the pleasure of making a daisy-chain was worth the
12    trouble of getting up and picking the daisies, when a white rabbit with
13    pink eyes ran close by her.</p>
14</blockquote>
15<?php if($_SERVER['HTTP_X_REQUESTED_WITH']==''){
16    include('footer.php');
17}?>
18

jQuery Code

js
1$(document).ready(function(){
2    $('.ajaxtrigger').click(function(){
3        var url = $(this).attr('href');
4        $('#target').load(url);
5        return false;
6    });
7});
8

Do you like my content?

Sponsor Me On Github