Welcome Guest, Not a member yet? Register   Sign In
Making a controller function only callable through AJAX?
#1

[eluser]D_Williams[/eluser]
One of the controllers I'm currently working on has a mix of "normal" controller functions and ones designed to be called by AJAX in my views.

Is there any way for me to test whether my function is being called from AJAX so I can prevent my function from being called in a browser?

Better yet, should I even bother? If somebody goes to mysite.com/whatever/ajaxfunction and it spews garbage output at them should I care? I can't think of any security risks in doing that...
#2

[eluser]Madmartigan1[/eluser]
Here is the source from CI 2.0 Input class:

Code:
/**
     * Is ajax Request?
     *
     * Test to see if a request contains the HTTP_X_REQUESTED_WITH header
     *
     * @return     boolean    
     */
    public function is_ajax_request()
    {
        return ($this->server('HTTP_X_REQUESTED_WITH') === 'XMLHttpRequest');
    }

You can also define this as a constant if you desire. I'm sure you can figure this out now Smile

I'd like to add that I use this method, and never write "ajax only" functions.
#3

[eluser]D_Williams[/eluser]
Hmm that seems like it'd do the job but I'm not using CI 2.0 yet.

I tried using the same code but I get

Code:
Fatal error: Call to undefined method Reporting::server() in /home/danny/Public/OpenCollect/application/controllers/reporting.php on line 27

when running it, so I assume older CI versions don't have the $this->server construct?
#4

[eluser]cahva[/eluser]
$this->server() is a method of the same class(Input). If you're using older CI, just add this to application/config/constants.php

Code:
define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');

After that you can use this in your controller:
Code:
if (!IS_AJAX)
{
    // Not an ajax call
}
#5

[eluser]Madmartigan1[/eluser]
As server() is a member of the input class, you would have to use $this->input->server()

Same things as $_SERVER.

Sorry I didn't clarify earlier.

I see cahva's method uses strtolower(), is there a reason for it?
#6

[eluser]D_Williams[/eluser]
Ahhh I was just misunderstanding. Got it now, works great.




Theme © iAndrew 2016 - Forum software by © MyBB