Welcome Guest, Not a member yet? Register   Sign In
is that possible to know if a function call in controller comes from client's AJAX request
#1

[eluser]datactrl[/eluser]
Hi, all

Is that possible to know wether a function call in a controller comes from client's Ajax request or a hyper link? Thank you in advance!

Jack
#2

[eluser]bretticus[/eluser]
Sure, just use post for your ajax requests (seems to be the default for jquery or prototype.) A normal hyperlink will always be get. (You can also get firebug for firefox and look for differences in the response headers.) So, if you are using "vanilla" ajax, here's an example using post:

Code:
var url = "/controller/action";
var params = "var1=one&var2=two";
http.open("POST", url, true);

//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");

http.onreadystatechange = function() {//Call a function when the state changes.
    if(http.readyState == 4 && http.status == 200) {
        alert(http.responseText);
    }
}
http.send(params);
#3

[eluser]mihailt[/eluser]
Code:
function isAjax() {
    return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest';
}
#4

[eluser]bretticus[/eluser]
Thanks mihailt. Is that prototype and jquery both? I certainly saw that with some ajax I knew was prototype. I tried a "vanilla" approach and no HTTP_X_REQUESTED_WITH header. However it's simple to add a custom header anyways for a "vanilla" call:

Code:
var url = "/controller/action";
var params = "var1=one&var2=two";
http.open("POST", url, true);

//Send the proper header information along with the request
http.setRequestHeader("X-Requested-With", "XMLHttpRequest");
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");

http.onreadystatechange = function() {//Call a function when the state changes.
    if(http.readyState == 4 && http.status == 200) {
        alert(http.responseText);
    }
}
http.send(params);
#5

[eluser]bretticus[/eluser]
nevermind, I found

X-Requested-With: XMLHttpRequest

with jquery as well. Certainly easier to check for a header.
#6

[eluser]TheFuzzy0ne[/eluser]
Code:
if ($this->input->server('HTTP_X_REQUESTED_WITH'))
{
    # It's an ajax request
}
else
{
    # It's not...
}
#7

[eluser]TheFuzzy0ne[/eluser]
An even neater approach might be to put this into your constants.php file:
Code:
define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');

Then you can simply use:
Code:
if (IS_AJAX)
{
   # ...

from within your controller method.




Theme © iAndrew 2016 - Forum software by © MyBB