dqiu
dqiu

Reputation: 337

how to differentiate ajax call and browser request in php (or codeigniter)?

is there a way to differentiate ajax call and normal browser request in php (or codeigniter to be specific)?

this is my jquery ajax call:

$(document).ready(function() {
    $('#container').load('http://localhost/index.php/customer/'); 
});

this is the index method of customer controller in codeigniter:

public function index() {
    //if (call == 'ajax request') 
    //  do this if it's an ajax request;
    //else
    //  do that if user directly type the link in the address bar;
    $this->load->view('customer/listview');
}

any help would be appreciated. thanks.

Upvotes: 5

Views: 1320

Answers (5)

Ravi
Ravi

Reputation: 737

Instead of relying on server variables which might get changed eg. if the server is behind a reverse proxy I do all my AJAX calls through a single javascript function in which I add a POST variable: isajax. Then I check for it using something like $this->UI->IsAJAX() which looks for a varible that was initialized while setting up the controller.

$this->_isAJAX = (empty($_POST['isajax']) ? true : false.

Upvotes: 0

Vamsi Krishna B
Vamsi Krishna B

Reputation: 11490

CodeIgniter way..

$this->input->is_ajax_request()

Upvotes: 6

JanLikar
JanLikar

Reputation: 1306

This is Codeigniter's implementation of this functionality.

if($this->input->isAjax()) {

        }  

Upvotes: 0

Philip
Philip

Reputation: 779

if (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {}

Should do what you need. Though it can obviously be faked like any other HTTP Header, so don't rely on it for anything major.

Upvotes: 1

ddinchev
ddinchev

Reputation: 34673

function getIsAjaxRequest()
{
    return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest';
}

Define this function somewhere then of course use it like this:

if (getIsAjaxRequest())
// do this
else
// do that

But there might be such thing already in CodeIgniter implemented, just global search for HTTP_X_REQUESTED_WITH

Upvotes: 4

Related Questions