V
V
vaflya2015-10-20 17:00:48
PHP
vaflya, 2015-10-20 17:00:48

Why doesn't PHP detect ajax request?

Good evening. On the Internet I found an example of defining an ajax request using php

if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    // Если к нам идёт Ajax запрос, то ловим его
    echo 'Это ajax запрос!';
    exit;
}
//Если это не ajax запрос
echo 'Это не ajax запрос!';


This code, accordingly, does not work for me (global variables, php settings, Apache, etc. I don’t know.) I read

on stackoverflow.com that this $servers variable is formed based on headers and they say that it cannot be trusted (link to the site lost with the question.)

A variant with $_GET['ajax'] and so on was offered.

What interests me the most.

Accordingly, you will have to make 2 copies of the page, page1.php and page1ajax.php? Just in the case of an ajax request, the page is given a jsone object.

If you think that it is possible in page1.php to determine whether an ajax request is an ajax request or not and accordingly give the necessary content, other questions arise:
1) Use include(), then you still have to do 2 scripts.
2) If without include(), then is it worth loading the script?

Solution: Thanks everyone! It just turned out that I was stupid. The guys were right about the headlines. In the js function for sending an ajax request using the get method, I did not specify a single header.

var xhr = ajax._init();
    xhr.open("GET", encodeURI(url), true);
                >>>>>>>>>>>xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
    xhr.send();
    xhr.onreadystatechange = function() {
  		if (xhr.readyState==4 && xhr.status==200) {
  			callback.call(xhr.responseText);
      }

Can someone help, everything works.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Skobkin, 2015-10-20
@vaflya

On stackoverflow.com I read that this $servers variable is formed based on headers and they say that it cannot be trusted (I lost the link to the site with the question.)

But Symfony developers - trust .
You'll look in the browser debugger to see if that header goes away. Perhaps this is your client code messing up - then you need to edit it.
And look in the PHP debugger to see what's going on in your headers.
UPD:
When you make an answer, don't forget to set the Content-Type in the headers to match the format in which you are giving.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question