Trying to transmit JSON data from a web page using JQuery, as shown below:
$.ajax({
type: "post",
url: "http://localhost/ajax/login",
data: '{username: "wiiNinja", password: "isAnub"}',
dataType: "json",
contentType: "application/json",
cache: false,
success: function(response, status) {
alert ("Success");
},
error: function(response, status) {
alert('Error! response=' + response + " status=" + status);
}
});
In the cake2.2 framework, there is a controller called Ajax with a method "login" as follows:
public function login($id = null)
{
if ($this->RequestHandler->isAjax())
{
$this->layout = 'ajax';
$this->autoLayout = false;
$this->autoRender = false;
$response = array('success' => false);
$data = $this->request->input();
debug($data, $showHTML = false, $showFrom = true);
}
return;
}
To verify correct data passing to the controller, check this line:
$data = $this->request->input();
The expected output of the debug printout should be:
{username: "wiiNinja", password: "isCool"}
A suggestion in CakePHP 2.x manual involves decoding the data:
$data = $this->request->input('json_decode');
If debugging outputs "null", adjust JavaScript post and controller code accordingly.
Changes made through personal experimentation revealed the following adjustments were needed:
Update Javascript code from:
data: '{username: "wiiNinja", password: "isAnub"}',
To:
data: '{"username": "wiiNinja", "password": "isAnub"}',
In the controller code, modify from:
$data = $this->request->input('json_decode');
To:
$data = $this->request->input('json_decode', 'true');
This resolved the issue.
To analyze the "$this->request->params" array after implementing suggestions:
array(
'plugin' => null,
'controller' => 'ajax',
'action' => 'login',
'named' => array(),
'pass' => array(),
'isAjax' => true
)
The necessary data was missing from the parameters despite appropriate routing setup. This aligns with documentation for CakePHP 2.x mentioned here:
http://book.cakephp.org/2.0/en/controllers/request-response.html
If sending a JSon string is not ideal, further adjustments are required to handle third-party codes efficiently.