Here’s a quick piece of code that i find useful to check if a request that comes to a PHP page was made via an Ajax call or a simple form post. This method uses the $_SERVER[‘HTTP_X_REQUESTED_WITH’] request to determine if data was sent to a specific page using an xmlhttprequest. It’s worth bearing in mind that there is no guarantee that every web server will provide this setting, servers may omit specific $_SERVER parameters, That said, a large number of these variables are accounted for, you can find more information about $_SERVER variables here.
]) && !
// If its an ajax request execute the code below
'This is an ajax request!'
//if it's not an ajax request echo the below.
'This is clearly not an ajax request!'
The code is pretty self explanatory we are literally checking to see if the request was sent via an xmlhttprequest. In the Demo below i’ve setup a page that contains a jQuery Ajax request to our code above and a simple form with a button that just submits to the same page.