I am finding myself implementing ajax into almost all my projects these days, the benefits are obvious: faster load times, richer interfaces, increased usability, and web 2.0 cred
Ideally AJAX powered sites should offer fallback functionality for those with javascript disabled, so we need a quick way of checking if the page was called via AJAX in our PHP code.
I normally build the following helpful function into my controllers:
function is_ajax() {
if (
isset($_SERVER['HTTP_X_REQUESTED_WITH'])
&& 'XMLHttpRequest' == $_SERVER['HTTP_X_REQUESTED_WITH']
) {
return true;
}
}
So now we can easily serve up some json to our ajax requests, and HTML for users without javascript.
if (is_ajax()) {
echo json_encode($data);
} else {
// load HTML view
}
Serving AJAX Requests with PHP
I am finding myself implementing ajax into almost all my projects these days, the benefits are obvious: faster load times, richer interfaces, increased usability, and web 2.0 cred
Ideally AJAX powered sites should offer fallback functionality for those with javascript disabled, so we need a quick way of checking if the page was called via AJAX in our PHP code.
I normally build the following helpful function into my controllers:
function is_ajax() { if ( isset($_SERVER['HTTP_X_REQUESTED_WITH']) && 'XMLHttpRequest' == $_SERVER['HTTP_X_REQUESTED_WITH'] ) { return true; } }So now we can easily serve up some json to our ajax requests, and HTML for users without javascript.
if (is_ajax()) { echo json_encode($data); } else { // load HTML view }voila.