Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell if a page is being called via Ajax, or on it's own

Tags:

jquery

ajax

php

I have a page that loads other pages via Ajax (think frames, except without the frames).

Obviously these pages can all be called independently, so I want to detect if they are being called via the Ajax, and if not, redirect to the main Ajax page.

The pages are php pages, so I have access to that as well.

index:

    goto = "StandalonePrograms.php";
    var clear = "<br style='clear:both;'>"
    if(goto != ''){
        $.ajax({
            url: goto,
            context: document.body,
            success: function(data){
                $('#mainwindow').html(data + clear);
                $('#mainwindow').find("script").each(function(i){
                    eval($(this).text());
                });
            }
        });
    }
like image 578
AndyD273 Avatar asked Mar 22 '12 18:03

AndyD273


1 Answers

Modern browsers add the following request header when a request is made using the XMLHttpRequest object:

X-Requested-With: XMLHttpRequest

In PHP, check the existence of this header using:

$_SERVER['HTTP_X_REQUESTED_WITH']
like image 124
Rob W Avatar answered Oct 18 '22 18:10

Rob W