Differentiate jQuery $.ajax requests
To ensure that your PHP application works both with and without Javascript enabled in the users browser it is often necessary to return different content depending on whether Javascript is enabled or not. For example often it is useful to return data via JSON when Javascript is enabled however it is unhelpful to display JSON to a user.
jQuery + Apache
jQuery (and most other major Javascript libraries) when executing AJAX requests use a specific header to show that they are doing so. This header can be requested and accessed as a variable as long PHP is installed as an Apache module. This method requires no change to your Javascript (jQuery) code however if PHP isn't installed as an Apache module there is a slightly less elegant workaround below that does require you to edit your Javascript.
<?php
$headers = apache_request_headers();
if( !empty($headers['X-Requested-With']) && ($headers['X-Requested-With'] == 'XMLHttpRequest')) {
header("Content-type: application/json"); }
}
?>
The above code firstly requests the headers and stores them in the variable $headers and then if the header is present sets the content type to application/json so that the browser treats the data as JSON. We use two clauses in the IF statement to avoid PHP displaying a warning about $headers['X-Requested-With'] being undeclared when Javascript is disabled.
Then when returning data (such as error information) you can use the same if statement to return a JSON encoded array if Javascript is enabled or just simple HTML if not.
jQuery with another webserver
PHP does not (to my knowledge) provide a platform independent method of getting the request headers. Therefore we can simply add another data field to our jQuery $.ajax request to be used as a differentiator.
$(".button").click(function() {
var firstName = $("input#firstName").val();
var lastName = $("input#lastName").val();
var email = $("input#email").val();
var dataString = 'firstName=' + firstName + '&lastName=' + lastName + '&email=' + email + '&js=1';
$.ajax({
type: "POST",
url: "add.php",
data: dataString,
success: function(result) {
// do something
}
});
return false;
});
By adding &js=1 to the request in the Javascript we can use the $_POST['js'] variable in PHP to differentiate between jQuery $.ajax requests and browser requests.
if (!empty($_POST['js'])) {
header("Content-type: application/json");
}
I hope you found this useful, if you have any comments or suggestions (especially on a more universal method of reading request headers) please let me know in the comments.
- Andrew Pryde

Saw Scott Pilgrim with 


