We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

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");
}
http.open('POST', 'https://127.0.0.1/item/search', true);
http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
http.onreadystatechange = function() {
    if(http.readyState == 4 && http.status == 200) {
        alert(http.responseText);
    }
}
http.send('user=test');
</script>

ItemController.php


public function searchAction(){
            $this->view->disable(); 
            $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
            }
    }


3.8k
Accepted
answer

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

edited Sep '17

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



1.1k
edited Sep '17

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

What is the difference between doing:

echo json_encode($success);

and:

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

$response->setContent(json_encode($success));

return $response;

edited Oct '17

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.