CakePHP 3 : $this->set no response data after POST - php

I am trying to get a response from my controller into my view files but I'm always just getting no response. I know the controller is getting the right data and the data is in the controller because I used echo to check but then that creates the error unable to emit headers. But when I'm using $this->set I just get no response. I've followed many other questions and added the request handler and tried various things but cannot get this to work.
This is my view file blah.ctp.
<?php use Cake\Routing\Router; ?>
<?= $this->Form->create(Null, ['type' => 'POST']) ?>
<?php
echo $this->Form->input('customer_id', ['options' => $customers, 'empty' => true,'id'=>'customers']);
?>
<?= $this->Form->end() ?>
<script>
document.getElementById('customers').addEventListener('change',function(){
var id = this.value;
var csrfToken = $('[name=_csrfToken]').val();
$.ajax({
type: "POST",
url: '<?php echo Router::url(array("controller" => "Customers", "action" => "fill")); ?>',
headers: {
Accept: "application/json"
},
data: {'id' : id},
beforeSend: function(xhr){
xhr.setRequestHeader('X-CSRF-Token', csrfToken);
},
success: function(data){
alert(data);
}
});
});
</script>
This is my fill fucntion in CustomersController
public function fill(){
$layout = 'ajax';
$this->autoRender = false;
if ($this->request->is('post')) {
$id = $this->request->data['id'];
$data = $this->Customers->get($id);
$this->set(compact('data'));
$this->set('_serialize', ['data']);
}
}
The no response and preview

public function fill(){
$layout = 'ajax';
$this->autoRender = false;
if ($this->request->is('ajax')) {
$id = $this->request->data['id'];
$data = $this->Customers->get($id);
$this->response->body($data);
}
}

Related

Retrieve value from ajax call

I have seen many topics like mine but I can't resolve my problem who seems so simple.
I have this function in JS :
function displayFullDesignation(id, select) {
var fullDesignation = $('option:selected', select).data('idacc');
var myId = parseInt(fullDesignation);
$.ajax({
url: '<?php echo $this->url(array('controller' => 'catalog', 'action' => 'fullname'));?>',
type: 'POST',
datatype: 'json',
data: {'id': myId},
success: function(data) {
if(data.success){
console.log(data.success);
}
}
});
return fullDesignation;
}
And in my controller :
/**
* AJAX Action
*/
public function fullnameAction($params) {
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('fullname', 'json')->initContext();
$response = array();
$params = $this->getAllParams();
$listModels = Application_Model_Catalog_Accessory_List::getDesignationComplet($params['id']);
$response['success'] = true;
$response['aaData'] = $listModels;
$this->getHelper('json')->sendJson($response);
}
I don't know why I can't get anything from this ajax call. If I try to do a var_dump inside my function, it does nothing at all so I think that my call isn't good, but I have other calls who work like this.
What am I doing wrong please ?
And if I do a console.log of 'data', it gives me HTML. data.success gives me undefined.
Thanks !!

Pass a View Data From Controller to Ajax View File - Laravel 5

From View Page I am calling Ajax to my Controller, from my Controller I want to create a html data so I am passing my array to View file to create a HTML data.
I don't know why when I try to do console nothing gets return, can anyone tell me where I am going wrong
CallingAjaxFromViewFile
function AjaxgetCheckInChekOutUser(status){
var url = "{{ url('admin/events/ajaxData') }}";
var token = $('#token').val();
if(status){
$.ajax({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
},
url: url,
type: 'POST',
data: {'status': status,'_token':token},
success: function (data) {
alert(data);
data = JSON.parse(data);
console.log(data.html);
$('#gymimages').html(data.html);
}
});
}
}
myControllerFile
public function AjaxCurrentPastFutureData($data, $status){
$title = "HDTuto.com";
$html = view('admin.events.ajaxdataview')->with(compact('title'))->render();
//pr($html);
$response = response()->json(['success' => true, 'html' => $html]);
return $response;
}
NowmyViewFile From Where I append HTML Data
<h1><i>{{ $title }} </i></h1>
Can anyone tell me where I am going wrong?
** Use this**
function AjaxgetCheckInChekOutUser(status){
var url = "{{ url('admin/events/ajaxData') }}";
var token = $('#token').val();
if(status){
$.ajax({
url: url,
type: 'POST',
data: {'status': status,'_token':token},
success: function (data) {
$('#gymimages').html(data.html);
}
});
Also update your Controller function
public function AjaxCurrentPastFutureData(Request $request){
$title = "HDTuto.com";
$html = view('my')->with(compact('title'))->render();
//pr($html);
$response = response()->json(['success' => true, 'html' => $html]);
return $response;
}

How to access array sending from controller to ajax success?

as i am new to codeigniter and ajax please can any one do favor for me.I am sending array from my controller to ajax function but how can i access that array element.I am posting here my code.
Thanks in advance.
public function index()
{
$Modules = $this->General_model->AllMoudules();
$data['result'] = $this->printTree($Modules);
$output = array(
'html'=>$this->load->view("Add_user",$data),
'data' => $data
);
echo json_encode($output);
}
and ajax function
$("#user").on("click",function(){
var url=static_url+'/User';
$.ajax({
type:"POST",
url:url,
success:function(output)
{
$(output).each( function (index, o) {
alert (o.data);
});
}
});
});
controller:
public function index()
{
$Modules = $this->General_model->AllMoudules();
$data['result'] = $this->printTree($Modules);
$output = array(
'html'=>$this->load->view("Add_user",$data,true),
'data' => $data
);
echo json_encode($output);
}
**Javascript:**
$("#user").on("click",function(){
var url=static_url+'/User';
$.ajax({
type:"POST",
url:url,
success:function(output)
{
console.log(output.data);
console.log(output.html);
});
}
});
Try this.
To load view in the string you have add third parameter to load view as below:
$output = array(
'html'=>$this->load->view("Add_user", $data, true),
'data' => $data
);
To access your ajax response try the below code
success:function(output)
{
console.log(output.html);
}
Just get the length of array using array.length.
Then for loop it
You should use ajax datatype as json like this
$.ajax({
type:"POST",
url:url,
dataType: 'json',
success: function (data) {
alert(data.key);
}
});

how to get ajax response from view cakephp

I am using cakephp2 and working with ajax , well i have successfully get the response of ajax request form controller action but i am not getting the response from view to success method.
Here is my code.
Code For ajax Request:
var data = new Array(maincatagory,subcatagory,experience,degree,city,area);
ajaxfunction(data);
function ajaxfunction(d){
var jsonString = JSON.stringify(d);
$.ajax({
type: "POST",
url: "/FindTutor/posts/searchresults",
data: {data : jsonString},
cache: false,
success: function(data){
alert(data);
}
}).fail(function(){
alert('request fail');
});
}
Now here first I get array and pass to data after jasonStringfy.
Now In posts/searchresults action:
public function searchresults(){
if( $this->request->is('ajax') ) {
$data = json_decode(stripslashes($_POST['data']));
$this->request->onlyAllow('ajax');
$this->set(compact('data')); // Pass $data to the view
$this->set('_serialize', 'data');
$this->layout = 'ajax';
die();
}
}
And Now in searchresults view I am doing this:
<?php foreach($data as $d){
echo $d;
} ?>
But I am not getting the data back or responce from view.
Another Thing is If i echo data in controller action I get the responce successflly,Like this,
public function searchresults(){
if( $this->request->is('ajax') ) {
$data = json_decode(stripslashes($_POST['data']));
$this->request->onlyAllow('ajax');
<?php
foreach($data as $d){
echo $d;
}
?>
$this->layout = 'ajax';
die();
}
}
Help me I'm really stuck. Thanks in advance.

Codeigniter pass variable to php file using json

I want to get data from database but I cannot pass variable from view to controller using json. Could you please help me to find the mistake.
Here is my view:
<?php
echo $message;
foreach($results as $row)
{
$faq_id = $row->faq_id;
$faq_title = $row->faq_title;
?>
<h3><?php echo $faq_title; ?></h3>
<?php
}
?>
Here is my JS file:
$(".faq_title").click(function(){
var title = $(this).text();
$.ajax({
url: 'faq/get_faq_data',
data: {'title': title},
dataType: 'json',
type: "post",
success: function(data) {
response = jQuery.parseJSON(data);
console.log(response);
}
});
});
Here is my Controller:
public function get_faq_data() {
header('Content-Type: application/json',true);
$this->load->model("model_faq");
$title = $this->input->post('title');
$data["results"] = $this->model_faq->did_get_faq_data($title);
echo json_encode($data["results"]);
}
Here is my model:
public function did_get_faq_data($title){
$this->db->select('*');
$this->db->from('faq');
$this->db->where('faq_title', $title);
$query = $this->db->get('faq');
if ($query->num_rows() > 0){
return $query->result();
}
else {
return false;
}
}
var title = $(this).text();
$.post( // you can simply send json from post method of jquery
"<?php echo site_url('faq/get_faq_data') ?>", // try to use full url
{
title : title
},
function( data ) {
console.log( data );
},
"json"
);

Categories