How To Determine Ajax Request in PHP?

In some case when requested with Ajax it came out with different result, if request is normal result will be different.In such circumstances first we need to know how to catch AJAX requests in PHP. Actually all we need to do just checking the value of HTTP_X_REQUESTED_WITH which is stored in the $_SERVER. Let's look at the example.

<?php
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
	// ajax request
} else {
    // else
}

If you wish you may convert to a function which is more useful and use it very easily. To give an example

function isAjaxRequest(){
    return !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}

Now we can use in this way

if (isAjaxRequest()){
    // ajax request
} else {
    // else
}

 

Comments

There are no comments, make the firs comment