Passing data between 2 controller functions - php

To put in simple words I want status1 to go to ajaxleadsreport controller
A bit more complex explanation:
I have 2 view classes called indexreport and ajaxleadsreport. ajaxleadsreport fetches all the data and displays it. Now I have a GET variable that is being passed to indexreport which I want to be able to pass it to ajaxleadsreport to filter the current data according to the GET variable that has been passed.
Controller Class:
public function listsreport($slug='')
{
$status1 = $this->input->get('status');
print_r($status1);
$main['content']=$this->load->view('crm/leads/indexreport',$content,true);
}
public function ajaxleadsreport($p='')
{
$output = array( 'html'=>$this->load->view('crm/leads/ajaxleadsreport',$content, true));
echo json_encode($output);
}
indexreport View Class:
<?php
$i=$return=$uriseg;
$post=$this->input->post(); $sess=$this->session->userdata();
$post = $post?$post:$sess;
?>
<div>
...
</div>
$(document).ready(function (){
getleads();
});
function getleads(p){
$.ajax({
type: "post",dataType:"json",async:false,cache:true,
url: "<?php echo site_url('leads/ajaxleadsreport'); ?>"+( parseInt(p)>0?'/'+p:''),
data: $('#objlistform').serialize(),
success: function(e){$('#leadswrap').hide().html(e.html).fadeIn('slow');}
}); return false;
}
ajaxleadsreport View class:
<?php
$sess=$this->session->userdata();
$status1 = $this->input->get('status');
// This is where I'm trying to put my GET value of status for filtering but it gives NULL.
$post = array('fstatus'=> $status,'fpriority'=> $sessn['fpriority']);
$postd = json_encode(array_filter($post));
?>
...
<script>
$(document).ready(function() {
function sendreq(){
setpostdatas();cleartable();getleads();
}
var slug = '<?php echo $slug?>';
var postd = '<?php echo $postd; ?>';
$('#item-list').DataTable({
"processing": true,
"stateSave": true,
"serverSide": true,
"ordering": false,
"ajax": {
url: "<?php echo site_url(); ?>leads/loadLeads",
data: {slug: slug, postdata: postd},
type : 'POST',
"dataSrc": function ( d ) {
d.myKey = "myValue";
if(d.recordsTotal == 0 || d.data == null){
$("#item-list_info").text("No records found");
}
return d.data;
}
},
'columns': [
{"data": "id", "id": "id"},
{"data": "lead_status", "lead_status": "lead_status"},
{"data": "priority", "priority": "priority"},
]
});
As you can see in the code above, I've tried $status1 = $this->input->get('status'); in ajaxleadsreport View class but the output for that is NULL, since the GET value is passed in my indexreport view class. When I do a print_r($status1) in indexreport controller it gives the right output, but NULL in ajaxleadsreport controller.
So basically now I need a way to pass this GET value to ajaxleadsreport controller.

You can use flashdata here:
Set your status to flashdata then get it out in ajaxleadsreport like this: (flashdata only exist once on next request)
$this->session->set_flashdata('status', $status1);
In ajaxleadsreport:
$this->session->flashdata('status');

In the controller class declare the variable:
protected $status1;
public function listsReport() {
$this->status1 = $this->input->get('status');
// [...]
}
Then you can access $this->status1 from any function that is invoked after.

Related

Display ajax posted array in codeigniter view

I need to display objects of an array in a view that has been posted to controller from another view.
Jquery ajax call
details is an array with few objects
$(document).ready(function () { // working
$("#nxt").click(function() {
var tmp = details;
var more_details = JSON.stringify(tmp);
$.ajax({
type: "POST",
url: 'http://localhost/application/index.php/Welcome/detailsLoad',
data: {more_details : more_details },
success : function(){
console.log('Posted');
location.href="http://localhost/application/index.php/Welcome/detailsLoad"
},
error: function(){
alert('Error!');
}
});
});
});
Controller
public function detailsLoad()
{
$moreDetails= $this->input->post('more_details');
$this->load->view('simulation',$moreDetails);
}
View
<?php
foreach($moreDetails['more_details'] as $result) {
echo $result['object1'], '<br>';
echo $result['object2'], '<br>';
}
?>
help me to modify and fix this code
If you want to data from the ajax call to move from your controller to your view you should set the name of the variable to be used inside your view:
$data = [];
$data['moreDetails'] = $this->input->post('more_details');
$this->load->view('simulation',$data);
Then you can use the variable $moreDetails inside the view:
foreach ($moreDetails as $result) {
echo $result['object1'], '<br>';
echo $result['object2'], '<br>';
}

Refreshing other view from jquery function

I write my application in PHP. I have this code:
$.ajax({
type: 'POST',
async: false,
url: $("#loginForm").attr('action'),
data: {
username: $("#username").val(),
password: $("#password").val()
},
dataType: 'text',
cache: false,
success: function(mess) {
console.log(mess);
if(mess=='true') {
console.log('true');
console.log(window.location.href);
window.location.href = "mainLogged";
$("#cao").html('homepage.php',"cao cao ovde sam");
} else {
$("#greska").html("Unesite ispravne podatke!");
$("#username").val("");
$("#password").val("");
}
}
}
When variable "mess" is 'true' I call controller mainLogged. I want to change a section with id "#cao" in homepage.php which is calling by controller mainLogged. Is this possible?
when you write window.location.href = "mainLogged"; the rest code is useless.
Now if you want to change some section here "#cao" you can do it in multiple ways
you can use cookie
you can use query params.
you can use session
Example using uri segment(query value) :
change this window.location.href = "mainLogged"; to this window.location.href = "mainLogged/1";
now catch it to controller like this
$seg = $this->uri->segment(2);
and in view check if $seg is 1 than do your staff
When you login you always end up in mainLogged controller's index function as there is no function mentioned, no need to send any query strings from the ajax, as you know that you ended up here after login. So, in this controller, just set a variable here for the value of the #cao and load it to the view.
function index(){
$data = array();
$data['cao'] = 'value_for_cao';
$this->load->view('view', $data);
}
Now, in the view you just echo out the value:
<input id="cao" value="<?php echo $cao ?>" />
Hope it helps.

How to pass data to controller to view using json in php?

I using codeigniter.I need to pass data to my controller to view somehow.I manage to pass view to controller(in view when drop-down selected value pass to controller using ajax)
this is my HTML code
<div class="form-group">
<label for="lastname" class="control-label">Your Packages</label>
<?php if(isset($tourbuddy_packages)){?>
<select id="itemType_id" class="form-control input-sm" name="tripbuddy_PackageTitle" onChange="disp_text()">
<?php
foreach ($tourbuddy_packages as $packages) {?>
<option value="<?php echo $packages['PackageID'] ?>"><?php echo $packages['PackageTitle']?></option>
<?php } ?>
</select>
<input type="hidden" name="PackageID" id="country_hidden">
<?php } else { ?>
<select class="form-control input-sm" name="tripbuddy_PackageTitle">
<option>Add Packages</option>
</select>
<?php } ?>
</div>
when drop-down selected a vale i pass data to controller by using ajax and java Script
$("#itemType_id").change(function() {
$.ajax({
url : "feature/tea/",
method: "POST",
data: "id=" + $(this).val(),
success: function(response) {
// handle
}
})
});
Selected vale pass to tea method in controller
public function tea()
{
$this->session->set_userdata(array('tripbuddy_PackageID'=>$_POST['id']));
$package_data = $this->ci->package_model->get_package($_POST['id']);
$package_cat = $this->ci->package_model->get_package_categories();
$data = array();
$data['tourbuddy_selected_package'] = $package_data[0];
$data['tourbuddy_selected_package_cat'] = $package_cat;
//echo $data['package']['AlbumID'];
$data['tourbuddy_selected_photos'] = $this->photo->get_package_photo_stream($data['tourbuddy_selected_package']['AlbumID']);
//echo var_dump($data['photos']);
echo json_encode($data);
}
now I need to pass $data array to my view without refreshing view page how can i do this ? need a quick help
First you need to add the correct header to your tea() function as it will be returning json
public function tea()
{
header('Content-Type: application/json');
//...
}
Then you will need to add the dataType parameter to your ajax call
$("#itemType_id").change(function() {
$.ajax({
url : "feature/tea/",
method: "POST",
dataType: 'json', //Added this
data: "id=" + $(this).val(),
success: function(response) {
// handle
}
})
});
In your success function you will then be able to access the data like
success: function(response) {
response.tourbuddy_selected_photos.data
}
Controller
class Feature extends CI_Controller
{
public function tea()
{
$post = $this->input->post(); //do some form validation here
$model = Model::get($post); // do all business logic in the model
if(!$model){
//return a Response header rather than a 404View
return $this->output->set_status_header(404);
}
$responce = array(
'something' => $model->something
);
return $this->output
->set_content_type('application/json')
->set_output(json_encode($responce))
->set_status_header(200);
}
}
Untested Javascript
var URL = <?php echo site_url(); ?>// Global URL variable
(function($){
var Form = {
init : function(){
this.Form = $("form#formId"),
this.ItemType = this.Form.find("#itemtype_id");
this.ItemType.on('change', $.proxy(this.change, this));
},
/**
* -----------------------------------------------------------------
* Bind the ItemTypeId change event to this function using $.proxy
* Ajax return's a deffered(promise) so capture it, and do stuff
* -----------------------------------------------------------------
**/
change : function(event){
this.doAjax(event.target).then(
function( data ) // success
{
$(this).html('Success'); // $(this) -> context
},
function( reason ) //fail
{
switch(reason.code)
{
case 404:
default:
$(this).html('no results found');
break;
}
}
);
},
/**
* -----------------------------------------------------------------
* Make the ajax request a wait for it to return a promise
* -----------------------------------------------------------------
**/
doAjax : function( target ){
var data = {
id : target.id
}
return $.ajax({
cache: false,
url : URL + 'feature/tea/',
context : target,
method: "POST",
data : data,
dataType : 'json',
}).promise();
}
}
Form.init();
}(jQuery));

how to get result array with getJson CodeIgniter

my code :
model :
function get_all_transaksi_proses() {
$rs = $this->db->query("SELECT a.id_transaksi, ETC");
return $rs;
}
control :
public function ambilDataTransaksi() {
$data=$this->transaksi->get_all_transaksi_proses();
echo json_encode(array("result" => $data->result_array()));
}
view :
$.getJSON("<?php base_url();?>transaksiDigorCont/ambilDataTransaksi", function(data) {
alert("jhjh");
});
this my code but it cant show alert("jhjh"), so it can't in to function(data) ?
You should be doing like:
$.getJSON( "<?php echo base_url(); ?>controllername/somefunction", function( data ) {
//do something with data
});
and in your controller, create a function say, 'somefunction', and
//controller code
function somefunction() {
//load model if not already done in constructor
//get data from model
$data = $this->your_model->get_all_transaksi_proses();
echo json_encode($data);
}
See the $.getJSON documentation:
jQuery.getJSON( url [, data ] [, success( data, textStatus, jqXHR ) ] )
It expects a URL as the first argument.

CakePHP trying to send a ajax request

I'm trying to send a ajax requistion to a controller, that it should returns something, but isn't.
My element (View/Elements/list.ctp):
<script type="text/javascript">
$(document).ready(function(){
$('#click').click(function(){
$.ajax({
type: "POST",
url: '<?php echo Router::url(array('controller' => 'products', 'action' => 'showProducts')); ?>',
success: function(data){
alert(data);
}
});
});
});
</script>
<p id="click">Click me!</p>
Controller products:
<?php
class ProductsController extends AppController {
public $helpers = array('Js' => array('Jquery'));
public $components = array('RequestHandler');
var $name = 'Products';
function showProducts(){
return 'This should to return in jQuery data';
}
}
?>
In cakePHP 2.x your controller needs to be in this way to return json data to the $.ajax request :
<?php
App::uses('AppController', 'Controller');
App::uses('JsBaseEngineHelper', 'View/Helper');
class AjaxtestsController extends AppController {
function beforeFilter() {
parent::beforeFilter();
}
public function returnsSomthing()
{
$layout = 'ajax'; // you need to have a no html page, only the data.
$this->autoRender = false; // no need to render the page, just plain data.
$data = array();
$jquerycallback = $_POST["callback"];
//do something and then put in $data those things you want to return.
//$data will be transformed to JSON or what you configure on the dataType.
echo JsBaseEngineHelper::object($data,array('prefix' => $jquerycallback.'({"totalResultsCount":'.count($data).',"ajt":','postfix' => '});'));
}
}
Improved Answer
You can use your controller's methods to search data on the db: find(), but I move the search queries to the Model:
First: Add the marked lines at the model code
App::uses('AppModel', 'Model');
App::uses('Sanitize', 'Utility'); // <---
App::uses('JsBaseEngineHelper', 'View/Helper'); // <---
Second: Create a Model method that executes the search:
public function getdata(){
$input = NULL;
$query = array();
$sql = NULL;
$data = array();
$i = 0;
$input = $_GET["name_startsWith"]; // <-- obtains the search parameter
$input = Sanitize::clean($input); // <-- prepares the search parameter
$sql = "select * from atable where condition like '".$input."%';";
$query = $this->query($sql); // <-- the model execute the search
if ($query){
$c = count($query);
for($i=0;$i<$c;$i++){ // <-- iterate over the returned data
$json['id'] = $query[$i][0]['id'];
$json['column1'] = $query[$i][0]['column1'];
$json['column2'] = $query[$i][0]['column2'];
$data[] = $json; // <-- the data it's stored on an multiarray, to be converted to JSON
}
}
$jquerycallback = $_GET["callback"];
echo JsBaseEngineHelper::object($data,array('prefix' => $jquerycallback.'({"totalResultsCount":'.count($query).',"search":','postfix' => '});')); //<-- the data it´s returned as JSON
}
Then: On the controller create a method to call the search
public function getdata()
{
$layout = 'ajax'; //<-- No LAYOUT VERY IMPORTANT!!!!!
$this->autoRender = false; // <-- NO RENDER THIS METHOD HAS NO VIEW VERY IMPORTANT!!!!!
$this->Cliente->getclient(); // <-- Get the data
}
You can call this method via ajax like this:
$.ajax({
url: "/application/controller/getdata",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 10,
name_startsWith: request.term
},
success: function( data ) {
response( $.map( data.search, function( item ) {
return {
value: item.id,
label: item.column1+" "+item.column2
}
}));
}
});
Check this for more info:
CakePHP Controller:autorender
CakePHP JsonView
Typo Quotes mismatch
Use double quotes to wrap
url: "<?php echo Router::url(array('controller' => 'products', 'action' => 'showProducts')); ?>",
^ ^
Problem
url: '<?php echo Router::url(array('controller' => 'products',
var ^ str^ var
controller and products are treated as variables not strings

Categories