Welcome Guest, Not a member yet? Register   Sign In
How to detect a Ajax request?
#1

[eluser]camille roux[/eluser]
Hello,

I'd like to use Ajax (surely Mootools) on my website, so I need a function to detect whether a request is from Ajax or not, because I want not to send the same data in each case.
Do you know how to do that?

Thank you
#2

[eluser]Doosje[/eluser]
Code:
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']=="XMLHttpRequest") {
        }else{
            // header("Location: " . base_url());
        }


this is how i do it.
#3

[eluser]coolfactor[/eluser]
Doosje, that's a very handy approach. Has it been your experience that that works with all Apache installs?
#4

[eluser]Doosje[/eluser]
You can just try it with vardump($_SERVER) and see if the 'extra' XMLHttpRequest is there.
If you use prototype & scriptaculous .. this works.... I don't know if you'd make your own library but i guess it works too.
#5

[eluser]camille roux[/eluser]
I'm sure there's a better way than using vardump... That looks like quite ugly, doesn't it?
#6

[eluser]Doosje[/eluser]
it's just for checking if the extra header "XMLHttpRequest" is there. .. nothing else..
You could do a echo $_SERVER['XMLHttpRequest']; but ... if it's called someting else, you could miss it. !
#7

[eluser]camille roux[/eluser]
I want to use Mootool, so I've just to find the name for the variable (XMLHttpRequest), test it and it's ok, isn't it?
#8

[eluser]Doosje[/eluser]
It sure looks like it..:-)

try my code ...and see what it does.
#9

[eluser]deviant[/eluser]
The code Doojse posted has worked for me in the past, didn't do any major compatibility tests though.
#10

[eluser]alexsancho[/eluser]
This code works with all major javascript frameworks, and it's easy to include in any ajax library, you only need to send this header with any ajax call.

I've extended the input library to add a function that return TRUE, FALSE,

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

in this way we can check ajax request with

Code:
if($this->input->isAjax()) {
        ...
    }




Theme © iAndrew 2016 - Forum software by © MyBB