Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Problem using the method isAjax()

Hello, I am trying to make Ajax requisitions and when I try check $this->request->isAjax() == true is always returning false but if I print inside the condition of isPost is working. my view: item/index.html.

<script type="text/javascript">
var http;
if (window.XMLHttpRequest) { 
    http = new XMLHttpRequest();
} else if (window.ActiveXObject) {
    http = new ActiveXObject("Microsoft.XMLHTTP");
}'POST', '', true);
http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
http.onreadystatechange = function() {
    if(http.readyState == 4 && http.status == 200) {


public function searchAction(){
            $request = new Request(); //  I  make this becaus I was triying $request->isAjax() 
            $response = new Response();
            $response->setHeader("Content-type", "application/json;charset=utf-8");
            if ($this->request->isPost() == true) {
                if ($this->request->isAjax() == true) {
                    //here is print nothing
                    $user = $this->request->getPost('user');
                    $sucess = array ('this' => $user);
                    echo json_encode($sucess);
                //here prints


Uh, I solve this setting the http.setRequestHeader('X-Requested-With', 'XMLHttpRequest '); in my JavaScript, my bad guys, hope this help anyone.

edited 29d ago

Naturally, as isAjax() method is only able to distinguish between browser and XHR request by reading HTTP headers XMLHttpRequest.

edited 23d ago

A semi unrelated question that came to mind when reading this thread.

What is the difference between doing:

echo json_encode($success);


$response = new \Phalcon\Http\Response();


return $response;

edited 15d ago

It is preferable to use framework's methods instead of raw PHP. The biggest benefit in your example is the fact that working with Response component / object, method will set Content type header as well, while plain echo of json_encode() will not.

And you're using it in a wrong manner - you don't need to json_decode() in setContent() method! Simply put your data (array or object) there, and it will call json_encode internally.