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.
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.
mypage. php: if(isset($_GET['ajax'])) { //this is an ajax request, process data here. }
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)
CodeIgniter way..
$this->input->is_ajax_request()
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With