How to access array sending from controller to ajax success? - php

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);
}
});

Related

How to get array in ajax response to another field

i have an array like
[{"id_pelanggan":"1","id_tipe":"5","nama_pelanggan":"ASD","alamat_jalan":"DS","alamat_kota":"1","alamat_provinsi":"ATA","kontak_pelanggan":"45454"}]
and my ajax
$(function() {
$("#autocomplete").change(function(){
var namaagen = $("#autocomplete").val();
$.ajax({
url: '<?php echo site_url('Pelanggan/tampil_where'); ?>',
type: 'POST',
dataType: 'json',
data: {
'namaagen': namaagen
},
success: function (agen) {
$("#napem").val(agen['nama_pelanggan']);
}
});
});
});
});
});
controller :
public function tampil_where(){
$nama = $this->input->post('namaagen');
$query = $this->pelanggan_m->tampilwhere($nama);
echo json_encode($query);}
models:
public function tampilwhere($nama){
$this->db->select('*');
$this->db->from('nm_pelanggan');
$this->db->where('nama_pelanggan',$nama);
$this->db->order_by('id_pelanggan', 'ASC');
$query = $this->db->get()->result_array();
return $query;
}
but nothing happen and i already add alert(agen['nama_pelanggan']); in response success and show alert undefined pls help , thanks for advance
Please change your alert code, right now you don't access response array in the proper way:-
alert(agen[0]['nama_pelanggan']);
Instead of:-
alert(agen['nama_pelanggan']);
Thanks

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;
}

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

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);
}
}

cakephp, jquery, .ajax()

I've been stuck with the retrieving of my sent variable trough an ajax POST function. Could you help me out?
My Jquery code:
$.ajaxSetup ({
cache: false
});
var selected = new Array();
$(document).ready(function() {
$('.value').click(function () {
if($(this).hasClass('strong'))
{
selected.splice(selected.indexOf(this.innerHTML), 1);
submitData(selected);
$(this).removeClass('strong');
}
else
{
selected.push(this.innerHTML);
submitData(selected);
$(this).addClass('strong')
}
});
});
function submitData(arDat) {
var arrayData = {"param1" : JSON.stringify(arDat)};
$.ajax({
type: 'POST',
url: 'http://localhost.local/coconut/trunk/challenges/values',
data: arrayData,
dataType: 'json',
success: function(data){
console.log(arrayData);
},
error: function(message){
alert(message);
}
});
}
My CakePHP Controller function:
function values() {
if ($this->RequestHandler->isAjax()) {
$this->autoRender = false;
Configure::write('debug', 0);
$params = json_decode($_POST['param1']);
//$result = json_encode($params);
$this->set('submitValue', $params);
} else {
$this->redirect(array('controller' => 'challenges', 'action' => 'index'));
}
}
And in a view.ctp file:
<?php debug($submitValue); ?>
But I get the following error:
Notice (8): Undefined variable: submitValue
In firebug I see this:
Parametersapplication/x-www-form-urlencoded
param1 ["Business","Life","Health"]
Source
param1=%5B%22Business%22%2C%22Life%22%2C%22Health%22%5D
Does anyone know what I'm doing wrong?
Thanks!
Edit:
A bit more clarification about what I want.. I want to use $this->set('submitValue', $params); (so $submitValue) elsewhere in another view.
The CakePHP function 'isAjax()' checks to see if a request is a Prototype Ajax request.
You aren't using Prototype, you're using jQuery - so presumably it's always returning false, and so submitValue is never set.

Categories