Dave Cameron
Dave Cameron

Reputation: 159

Detect Ajax in PHP

I am trying to make an ajax post to the same php page.

Ajax:

$("#loginForm").submit(function(e) {
    e.preventDefault();
    var postData = $(this).serialize();
    $.post("login.php", postData);
});

The postData is correct and is in the following format:

username=john&password=123123

PHP (same page):

if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
      echo 'Ajax Request Detected';
}

However this if-check always returns false and the echo line is never executed. What am I doing wrong here?

Upvotes: 3

Views: 6266

Answers (5)

seddass
seddass

Reputation: 376

This is the correct way to detect ajax requests in php:

if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') {
    // this is ajax request, do something
}

Upvotes: 9

Emmanuel David
Emmanuel David

Reputation: 411

I tried all the suggested answers but the one that worked for me is using the below code

if (strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false) {
  //this request expects json
  die('json expectd');
}
die('non json');

I am currently using axios without modifying any header setttings.

Depending on your javascript package you may need to define the ACCEPT in the headers for this to be effective for you.

But with most AJAX packages this is always there by default and it works fine.

Upvotes: 0

tofsjonas
tofsjonas

Reputation: 61

In vanilla javascript, you need to add this to your ajax:

xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

I have no idea how it is done in jQuery though, but it should be doable.

Upvotes: 0

Stefan Jansen
Stefan Jansen

Reputation: 591

The header you are searching for is called 'X-Requested-With' (value XMLHttpRequest) and cannot be retrieved with $_SERVER['HTTP_X_REQUESTED_WITH'].

You could have found this yourself using a var_dump on the $_SERVER variable. alternatively, you also could use your browser to find out what the headers sent were.

Getting the request headers in your script, can be done with the getallheaders function.

https://www.php.net/manual/en/function.getallheaders.php

Upvotes: 1

msander
msander

Reputation: 476

I would suggest to use a GET parameter for identifying AJAX requests. $_SERVER depends on the webserver and the javascript framework.

-> Change your URL to login.php?ajax=1 when using AJAX.

Upvotes: 1

Related Questions