JQuery – Detect AJAX Requests with PHP

Certainly, for the huge majority of our projects, we can’t only rely on JavaScript for things like validation, or AJAX requests. What happens when JavaScript is turned off? For this very reason, a common technique is to detect whether an AJAX request has been made with your server-side language of choice.

jQuery makes this ridiculously simple, by setting a header from within the $.ajax method.

 // Set header so the called script knows that it's an XMLHttpRequest
 // Only send the header if it's not a remote XHR
 if ( !remote ) {
 xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
 }
 

With this header set, we can now use PHP (or any other language) to check for this header, and proceed accordingly. For this, we check the value of $_SERVER[‘HTTP_X_REQUESTED_WITH’].

Leave a Reply

Your email address will not be published. Required fields are marked *

*