views:

116

answers:

4

I have an ajax script (jquery) that asks index.php to output generated variables. This index.php is also the file where the whole page is generated and initially populated with data. How can I only let the getNewData() function when ajax requests this file. Right now it duplicates the entire page and outputs it so there is two of everything.

+2  A: 
    function isAjax() {
            return env('HTTP_X_REQUESTED_WITH') === "XMLHttpRequest";
    }

Try this... from CakePHP

Dooltaz
unfortunately im using my own framework.
+1  A: 

Ideally you probably shouldn't have everything all in the index.php file. But, you could proably pass a GET variable with the AJAX request and check for that in the PHP file:

if ('requestType' == 'ajax')
{
    // return json etc
}
else
{
    // print page
}
jeef3
+1  A: 

If i am right you need to conditionally execute this method. So send an asynchronous request using an extra param

$.get('/index.php?exec=1);

In index.php

if($_GET['exec']==1){
     //execute
}
else {
  //render page - output html, etc
}
andreas
+2  A: 

A native PHP implementation of Dooltaz's answer would be as follows:

function isAjax() {
    return $_SERVER['HTTP_X_REQUESTED_WITH'] === "XMLHttpRequest";
}

This of course, is contingent on the X_Requested_With header actually being sent by the clients XHR request. As far as I know, all major Javascript libraries do include this header, but if you're rolling on your XHR implementation, you'll need to add it.

jason