Published by Mijingo

tips icon image

EE Insider Tips
Sponsored by Mijingo's EE 2 Screencasts

ExpressionEngine mini-howtos created by the EE Insider community.

AJAX Request Code

  • Posted by Kenny Meyers
  • June 02, 2009

In many frameworks there is a way to test if a request is AJAX or not. Sometimes I need to request partial templates with some EE code on them that I want to be accessible via AJAX only. I turn on PHP parsing on “before” and use the following.

<?php
    $AJAX 
= (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'== 'XMLHttpRequest');
    if (
$AJAX){
?>

//Ajax code goes here

<?php } else {  ?>

// Non Ajax code goes here, a redirect if you will

<?php } ?> 

Special thanks to Leevi Graham for the beautiful code. Buy his awesome extensions and add-ons.