user2741109
user2741109

Reputation: 121

Check if included file is used by ajax or php

I created a system where the HTML is built by php or ajax. Because the HTML is nearly the same I decided to create an include file for that so the php and the javascript can use the file. The question is if there is a way to look if an included file is currently used by an ajax function or by php?

Here is some example code for better understanding what I mean:

$variable = "";

if (this include file is currently used in an ajax function) {
    $user = \'+variable[0]+\';
    $content = \'+variable[1]+\';
}

$variable .= '<div>';
$variable .=     '<a href="'.$user.'">'.$user.'</a>';
$variable .=        '<div><p>'.$content.'</p></div>';
$variable .= '</div>';

Hopefully you understand what I mean :D

Upvotes: 0

Views: 127

Answers (3)

Brandon - Free Palestine
Brandon - Free Palestine

Reputation: 16676

More info: http://davidwalsh.name/detect-ajax

if (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    $is_ajax = true;
}

Depends on what you are using for AJAX, but most modern libraries (E.g. jQuery) send that header. Not all web servers will provide this header either, so it's not 100% reliable.

Upvotes: 0

w00d
w00d

Reputation: 5606

It is more reliable to check whether it is included by php since it's a server-side-controlled check. Suppose that file is name to_be_included.php

In the somefile.php file you use to include to_be_included.php:

define("MY_APP");

and then in to_be_included.php. Do a check:

if (!defined("MY_APP")) { 
  // accessed by ajax
} else {
  // accessed by php
}

Upvotes: 1

rAjA
rAjA

Reputation: 919

In your php,

    $ajax = 0;
    if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
    {
        $ajax = 1;
    } 
    elseif (isset($_POST['HTTP_X_REQUESTED_WITH']) && strtolower($_POST['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') //this is an optional method 
    {
         $ajax = 1;
    }

define('IS_AJAX', $ajax);

and in your front end code,

$.ajax({
  type: "POST",
  url: URL,
  data: {"HTTP_X_REQUESTED_WITH":"xmlhttprequest"}
}).done(function( data ) {
});

and in your original code,

$variable = "";
if (IS_AJAX) {
    $user = \'+variable[0]+\';
    $content = \'+variable[1]+\';
}

Upvotes: 0

Related Questions