1

I was wondering if there is a way to check if a PHP page was called by an Ajax request. I have a page that shows a form for update some data on database (update.php) but I want to make it accessible only if it was called by a page called "change_image.php", because I won't show the form if called by direct link, as it will be without CSS and javascript, because they are included in the first page (update.php).

I saw this answer on StackOverflow, but it is without explanation and I don't know if it is the right way to do that: Link to answer

The code of the answer is that:

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
/** Yes, it was an ajax call! */ 
/* I can call create_mosaic() function here 
 after checking if images have been loaded*/
}
SAVe
  • 814
  • 6
  • 22
  • 1
    Most JS frameworks send such an extra header when making AJAX requests - you need to figure out which one the one you are using sends (if any), resp. add such a header to your code, if you are doing your AJAX request by using the native XMLHttpRequest object … – 04FS Jul 03 '19 at 08:30

2 Answers2

1
public function isAJAX() {
  return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest';
}

This is a slightly different version. First checking if HTTP_X_REQUESTED_WITH is set and equals XMLHttpRequest which is a flag that most frameworks use (send) with their AJAX requests.

You could also simply send your own variable with every AJAX request you make and check it on your AJAX endpoint.

For example:

$.ajax({
  url: url,
  data: {
    requestType: 'AJAX'
  },
  type: 'GET'
});

And on your PHP endpoint:

if (isset($_GET['requestType']) && $_GET['requestType'] === 'AJAX') {

  // This is an AJAX request
}
MrUpsidown
  • 21,592
  • 15
  • 77
  • 131
1

Have a look at the link below

Does $_SERVER['HTTP_X_REQUESTED_WITH'] exist in PHP or not?

Abhishek Patil
  • 1,373
  • 3
  • 30
  • 62