I would like to check server-side if a request to my php page is an ajax request or not.
I saw two ways to do this:
First way: sending a GET
parameter in the request which tells the page that this is an AJAX request (=mypage.php?ajax
)
mypage.php:
if(isset($_GET['ajax'])) { //this is an ajax request, process data here. }
Second way: set a header to the xmlHttpRequest
:
client-side js:
xmlHttpRequestObject.open(“GET”,url,true); xmlHttpRequestObject.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
mypage.php:
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' ) { //request is ajax }
The fact is, those two ways of doing it can easily be hacked, so it's not secure to check if i get an AJAX request like this.
How can i check if i'm receiving an AJAX request?
The X-Requested-With header returns a string that indicates whether it's an Ajax request or not. An Ajax request will have this header set to XMLHttpRequest.
ajax() : $. ajax({ type: 'POST', url: 'page. php', data: stuff, success: function( data ) { }, error: function(xhr, status, error) { // check status && error }, dataType: 'text' });
An AJAX request is a request made by an AJAX application. Typically, it is an HTTP request made by (browser-resident) Javascript that uses XML to encode the request data and/or response data.
Here is the tutorial of achieving the result.
Example:
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') { exit; } continue;
This checks if the
HTTP_X_REQUESTED_WITH
parameter is not empty and if it's equal toxmlhttprequest
, then it will exit from the script.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With