Reputation: 9800
I'm working in CakePHP 3.4
I'm making an Ajax request to controller for fetching some data from database and response it back to the view. Since, the data returned is a set of data which can be from 1 row to 100 rows. I want to make a separate view and send response data to that view and then replace div content with that view.
This is how ajax call is being made
$('#trigger_connect_btn').click(function(e) {
e.preventDefault();
var data = {server_id : $('#server_id').val()};
$.ajax({
type: 'post',
data: data,
url: '/servers/trigger-connect',
success: function(result){
console.log(result);
}
});
});
and triggerConnect()
action
public function triggerConnect()
{
$this->autoRender = false;
$id = $this->request->getData('server_id');
$server = $this->UserServers->get($id);
$ftp = new \FtpClient\FtpClient();
$ftp->connect($server->server_url);
$res = $ftp->login($server->server_username, $server->server_password);
if ($res) {
$response['code'] = 100;
$response['type'] = 'Success';
$response['message'] = 'Login Success';
$response['content'] = $ftp->scanDir();
} else {
$response['code'] = 101;
$response['type'] = 'Error';
$response['message'] = 'Login Failed';
}
echo json_encode($response);
}
current view file has
<div id="response-content"></div>
This is working fine and returned content is printing in console. I know, I can iterate through data and print in view using jQuery but I want to create a separate view file for it which will render the returned data and then update a div in current view file with rendered view.
Upvotes: 0
Views: 2326
Reputation: 2195
Well, there is jquery load method for you if you want to load particular CakePHP method with it's view file.
$('#trigger_connect_btn').click(function(e) {
e.preventDefault();
$("#response-content").load("/servers/trigger-connect", {
server_id : $("#server_id").val()
});
});
The above script will load the corresponding view of function trigger-connect
to #response-content
.
And now comment out / delete the following line in your action , and make sure you have set variable to iterate that in your corresponding view just as you need.
// $this->autoRender = false;
Upvotes: 1