1
votes

I want to send data and get response as JSON for fast response. So i am using AJAX. Why i am getting

"Content-Type text/html; charset=UTF-8"

Why not getting

Content-Type application/json

Controller

 public function testingMethod() {
        $this->autoRender = false;
        $urlVal = $_POST['urlVal'];
        $dataBack = json_encode($urlVal);
        if ($this->RequestHandler->isAjax()) {
            return $dataBack;
        }
    }

jQuery

$.ajax({
      type: "POST",
      url: pathname+"Frontends/testingMethod",
      data: 'urlVal=' + urlVal, 
      dataType: 'json',
      success: function (result) {
        console.log(result);
        alert(result);
     }
    });

Header

Response Headers

Connection  Keep-Alive
Content-Length  2382
Content-Type    text/html; charset=UTF-8     //why here not getting application/json
Date    Wed, 14 Aug 2013 10:17:38 GMT
Keep-Alive  timeout=5, max=94
Server  Apache/2.2.22 (Win32) PHP/5.4.3
X-Powered-By    PHP/5.4.3
1
I'm not familiar with JQuery, but you almost certainly need to set a "Content-Type" header value (to "application/json") when you perform the POST. Otherwise it probably just defaults. - brianmearns
You’re not actually sending a Content-Type header, that’s why. - Martin Bean

1 Answers

2
votes

Quick checklist:

  1. Add the .json extension to routes.php:

    Router::parseExtensions('json');
    
  2. Load the RequestHandler class in your controller:

    public $components = array(
        'RequestHandler',
    );
    
  3. Create a json folder inside your model's View directory and place JSON view there.

  4. Append .json to the URL:

    url: pathname+"Frontends/testingMethod.json",
    

This is documented at JSON and XML views. It's worth reading the full document because the steps I've described are not the only possible way to do it.