Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 964
dqiu Avatar asked Aug 04 '11 10:08

dqiu


People also ask

What is the difference between Ajax request and HTTP request?

An AJAX request is just an HTTP request made by JavaScript code. Browsers load web pages by sending requests to the server using HTTP. Each time a page loads, a request is made. JavaScript code can do the same thing, but without needing to reload the whole page.

How do I know if I have an Ajax request?

mypage. php: if(isset($_GET['ajax'])) { //this is an ajax request, process data here. }

What type of requests does Ajax use between the server and the browser?

AJAX just uses a combination of: A browser built-in XMLHttpRequest object (to request data from a web server) JavaScript and HTML DOM (to display or use the data)


3 Answers

CodeIgniter way..

$this->input->is_ajax_request()
like image 159
Vamsi Krishna B Avatar answered Oct 05 '22 06:10

Vamsi Krishna B


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

like image 38
ddinchev Avatar answered Oct 05 '22 05:10

ddinchev


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.

like image 25
Philip Avatar answered Oct 05 '22 05:10

Philip