0

is there difference whether when a page called with ajax when called normally? I mean how i could figure out a page called with ajax or called directly ?

Hamid
  • 141
  • 1
  • 2
  • 7
  • possible duplicate of [Detect Ajax calling URL](http://stackoverflow.com/questions/3124636/detect-ajax-calling-url) – Pekka Apr 18 '11 at 15:53

2 Answers2

0

To distinguish between a normal page load, and an AJAX load ... some might code into the JS a variable to pass to the PHP page that indicates AJAX. This would let you modify output as JSON or whatever you wish to do.

Others use separate php scripts for AJAX.

But yeah, there are many ways to figure this out. More details if you have questions, but these are probably the easiest.

Edit: If you did not see the URL posted as the main comment as possible duplicate. this should answer your question about identifying ajax requests only.

Most well-known Ajax frameworks like jQuery and mooTools add a specific header which you can check with PHP:

if (strcasecmp('XMLHttpRequest', $_SERVER['HTTP_X_REQUESTED_WITH']) === 0)
{
    // Ajax Request
}
David Houde
  • 4,835
  • 1
  • 20
  • 29
  • so think i add a extra variable when i wanna use ajax ( somthing like ajax=true ) is it safe way ?when i use ajax function output will echo as JSON encode and it's not nice when anyone write url and append "ajax=true" in end of url see encode json code! is any way safe than this way ? – Hamid Apr 18 '11 at 18:25
  • I'm not 100% sure, but I personally wouldn't worry about people accidently seeing JSON when they intentionally go to the JSON URL. This will allow you to test your code if needed, and you should not be giving any sensetive data through the JSON response that you do not give in the normal page request -- don't assume the user wont be able to see it, cause that is always possible. You might consider using POST instead of GET on the AJAX request, this will makes it harder for someone to accidentally access it via their browser url with GET. Good luck! – David Houde Apr 19 '11 at 12:20
0

You can add a parameter to the call, for example:

xmlhttp.open("GET","page.php?request=ajax",false);

And then check for it in php:

if($_GET['request'] == 'ajax'){
    //this was called by ajax!
}
Ortiga
  • 8,455
  • 5
  • 42
  • 71