Is there a way (in PHP) of detecting if the script call was caused by a jQuery load or not?

I would like the script to detect if jquery is called

If not, it will render the page + layout, if not, it will just be for the content (but it doesn't matter)

But yes, a way of detecting if it was triggered by a jquery load - ajax - or requested directly.

Hooray!

+2


source to share


4 answers


Can't you send a GET parameter with the load?

Those:

jquery=1 //(for load)

jquery=2 //(for the 'low-level' ajax call)

      



Any other value for normal loading script

Then you give the PHP script the ability to determine what to do next. Reading the meaning$_GET['jquery']

+6


source


You might want to take a look at the HTTP headers your server receives.

For example, let's say I have this page:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.js"></script>
</head>
<body>
    <div id="test"></div>
    <script type="text/javascript">
        $('#test').load('temp.php');
    </script>
</body>
</html>

      

And the temp.php script contains just this:

<?php
var_dump($_SERVER);

die;

      


When load

executed, the "test" <div>

will contain a dump $_SERVER

; and it will include this, among others:



'HTTP_X_REQUESTED_WITH' => string 'XMLHttpRequest' (length=14)

      

XMLHttpRequest

is the object that was used to create the Ajax request.


This means that you should be able to determine if the request was made with an AJax request, with something like this:

if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])
    && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
    echo "Ajax";
} else {
    echo "Not Ajax";
}

      

With this, you can determine if your page is called "usually" or with an Ajax request and decide whether to include layout or not.


BTW: This is exactly the solution that Zend Framework uses to detect Ajax requests for example .

+14


source


If I recall correctly, the jQuery AJAX functions are sending the header X-Requested-With

(with value XMLHttpRequest

).

+6


source


If you are using Zend Framework you can use

// in one of your controllers
if ($this->getRequest()->isXmlHttpRequest()) {
  // ...
}

      

http://framework.zend.com/manual/en/zend.controller.request.html

+1


source







All Articles