AndyD273
AndyD273

Reputation: 7279

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

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());
                });
            }
        });
    }

Upvotes: 9

Views: 6882

Answers (2)

user3544556
user3544556

Reputation:

You cannot never trust clients and their sent information! The headers can be spoofed by hackers (for example with cURL) and even HTTP_X_REQUESTED_WITH is not reliable. there is no 100% trusted way to know that. The Only way is using captcha...

Upvotes: -1

Rob W
Rob W

Reputation: 348992

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']

Upvotes: 16

Related Questions