Display ajax posted array in codeigniter view - php

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

Related

Yii2 pass big array from one view to another controller

I have big array, it is result of controller
public function actionAaaa()
{
//somoethig, effect array
return $this->render('test', [
'array' => $array
]);
}
For example in view:
<pre>
<?print_r($array);
</pre>
Now I want pass this array from view to another action controller.
I don't know how do this.
I'm try:
<button type="submit" id="test" class="btn btn-lg btn-primary">Test</button>
<script>
$(document).ready(function () {
$("#test").click(function () {
var variable = <?=$array?>;
//alert($(this).attr('id'));
$.ajax({
type: "POST",
url: 'controller/action',
data: variable,
success: function (data) {
alert("success!");
}
});
});
});
</script>
but when I try use next controller, I don't see anything:
public function actionBBBB()
{
$request = Yii::$app->request;
$tablica = $request->post();
echo 'Tablica POST';
echo '<br />';
echo '<pre>';
print_r($tablica);
echo '</pre>';
echo '<br />';
echo 'XXXxxxXXX';
}
Any idea?
You are not able to post the entire array like that. You can however serialize it to do so:
var variable = <?serialize($array);?>
Then you can unserialize it later.
This is just one alternative. Some would say its bad. Probably is. You can also use SESSION

codeigniter ajax not setting sessions asynchronously

I am new to codeigniter ajax and i have a problem with sessions.My sessions are not being set and unset
asynchronously and i have to refresh the page just to see the changes.
view/header:
<?php
if(!empty($product)){
$pid=$product[0]['product_id'];
}
?>
<script>
$(document).ready(function(){
if($('.add_to_basket').find('img')){
$('.add_to_basket').click(function(){
var message=$('#badgemessage');
$('#msgcart').append(message);
message.show('slow');
var trigger=$(this);
var param=trigger.attr("rel");
var item=param.split("_");
$.ajax({
type: 'POST',
url: '<?= base_url()."cart_c/myfunk/".$pid?>',
data: { id: item[0], job: item[1] },
dataType:'json',
success: function(data) {
console.log(data);
},
error:function(){
alert("error");
}
});
return false;
});
}
});
</script>
model/basket_model:
<?php
class Basket_model extends CI_Model{
function activeButton($sess_id){
$e=$this->session->userdata('basket');
if(isset($e[$sess_id])){
$id=0;
$label="<img src='".base_url()."images/remove.png' />";
}else{
$id=1;
$label="<img src='".base_url()."images/add.png' />";
}
$out="<a href='#' class='add_to_basket' rel='".$sess_id."_".$id."'>".$label."</a>";
return $out;
}
function setItem($pide,$qty=1){
$e=$this->session->userdata('basket');
if(isset($e)){
$e[$pide]['qty']=$qty;
$this->session->set_userdata('basket',$e);
}else{
$arr=array($pide=>array('qty'=>$qty));
$this->session->set_userdata('basket',$arr);
}
}
function removeItem($pide,$qty=null){
$e= $this->session->userdata('basket');
if($qty != null && $qty < $e[$pide]['qty']){
$e[$pide]['qty']=($e[$pide]['qty']-$qty);
$this->session->set_userdata('basket',$e);
}else{
$e[$pide]=null;
unset($e[$pide]);
$this->session->set_userdata('basket',$e);
}
}
}
?>
controller/cart_c:
<?php
class Cart_c extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('catalogue_model');
$this->load->model('products_model');
$this->load->model('basket_model');
}
function myfunk($id){
if(isset($_POST['id']) && isset($_POST['job']))
$out=array();
$pid=$_POST['id'];
$job=$_POST['job'];
if(!empty($id)){
switch($job){
case 0:
$this->basket_model->removeItem($pid);
$out['job']=1;
break;
case 1:
$this->basket_model->setItem($pid);
$out['job']=0;
break;
}
echo json_encode($out);
}
}
}
?>
controller/products:
<?php
class Products extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('catalogue_model');
$this->load->model('products_model');
$this->load->model('basket_model');
}
function product($id){
$kitties['cats']=$this->catalogue_model->get_categories();
$data['product']=$this->products_model->get_product($id);
$data['active_button']=$this->basket_model->activeButton($id);
$this->load->view('header',$data);
$this->load->view('sidebar',$kitties);
$this->load->view('product',$data);
$this->load->view('footer');
}
}
?>
view/product:
<div class="contentwrap">
<div id="content_area">
<?php
$e=$this->session->userdata('basket');
print_r($e);
if(!empty($product)){
foreach($product as $p){
?>
<h1><?=$p['product_name']?></h1>
<div id="product_image">
<img src="<?=base_url()?>/images/<?=$p['image']?>" width="400" height="300" />
</div>
<div id="product_desc">
<?=$p['description']?>
<br><br>
<?=$active_button?>
</div>
<?php
}
}else{
echo "Product unavailable";
}?>
</div>
</div>
The problem is my $active_button in the product view is not changing asynchronously but the sessions are being set and unset
i can see items being pushed into and out of the session array when i refresh the page.When i hit the button my chrome console displays: object{job:0}
ok after looking and studying youre code. you can implement what you want by retrieving the button again when making your AJAX call. The way to retrieve it is by calling that model again, then using jquery to replace the current button. Try the following:
Controller - Cart_c
function myfunk($id) {
if (isset($_POST['id']) && isset($_POST['job'])) {
$out = array();
$pid = $_POST['id'];
$job = $_POST['job'];
if (!empty($id)) {
switch ($job) {
case 0:
$this->basket_model->removeItem($pid);
$out['active_button'] = $this->basket_model->activeButton($pid);
break;
case 1:
$this->basket_model->setItem($pid);
$out['active_button'] = $this->basket_model->activeButton($pid);
break;
}
echo json_encode($out);
}
}
}
JS in header view:
<script>
$(document).ready(function() {
function add_to_basket($this) {
var param = $this.attr("rel");
var item = param.split("_");
$.ajax({
type: 'POST',
url: '<?= base_url() . "cart_c/myfunk/" . $pid ?>',
data: {id: item[0], job: item[1]},
dataType: 'json',
success: function(data) {
console.log(data);
$this.replaceWith(data.active_button);
$('.add_to_basket').click(function() {
add_to_basket($(this));
});
},
error: function() {
alert("error");
}
});
return false;
}
$('.add_to_basket').click(function() {
add_to_basket($(this));
});
});
</script>
Ok I think perhaps we should start by discussing the proper flow of your app. Assuming that your URL looks something like this Products/product/10 and you intially load the page, your function runs providing you with right button and products as expected.. Lets say in this case product 10 does not exist in the session/cart so you see the ADD image button come up.. All good.. Now, when you click add, and from what you are saying, it adds the product to the session/cart, and you get a return JSON of ‘job:0’. So far it works as expected from the code I am seeing. A return of job:0 means that you ran the setItem function. Now the problem you are saying is that the view “is not changing asynchronously”. By this, do you mean that you expect the page to reload and run the function again so that the image can now say “remove”?

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

AJAX and Codeigniter Controller

I want to dynamically parse RSS feeds.
I have a select list and I would like to send a value (id) to the controller with ajax.
and after, I want to parse RSS feeds corresponding to the id
My Controller home.php :
function view($type = NULL)
{
$data = array();
$this->load->model('flux_model');
if ($type == "ajax") {// load ajax view
$flux = $this->flux_model->get_one_flux($this->input->post('id'));// ajax id
$flux2 = $flux[0]->url_flux;
$xml = new SimpleXMLElement($flux2, NULL, TRUE);
//my foreach
$this->load->view('messages_list', $data);
}
else{ // load the default view
$nb_min = 0;
$nb_max = 7;
$nombre = mt_rand($nb_min,$nb_max);
$flux = $this->flux_model->get_one_flux($nombre);
$flux2 = $flux[0]->url_flux;
$xml = new SimpleXMLElement($flux2, NULL, TRUE);
//my foreach
$this->load->view('default', $data);
}
}
Ajax script :
$("#myform1 #rss").change(function(){
var msg = $('#myform1 #rss').val();
$.post("<?= site_url('home/view/ajax') ?>", {id: msg}, function() {
$('#main').load("<?= site_url('home/view/ajax') ?>");
$('##myform1 #country').val('');
});
});
view default works, I parse an RSS feed randomly
but with the ajax view, I have this error:
Message: SimpleXMLElement::__construct(): I/O warning : failed to load external entity ""
it looks like I do not get the id?! ajax problem?
I think your issue is with
$.post("<?= site_url('home/view/ajax') ?>" [etc.]
Because many sites' configurations will prevent cross-site Ajax requests (See XSS), your $.post will be prevented. Instead, try something like:
$.post("controller/method/parameters" [etc.]
Example:
In your JavaScript:
$.post("ajax/myajax/myparam",{},function(data) { alert(data); });
And in your controllers/ajax.php file:
class Ajax extends CI_Controller
public function __construct()
{
parent::__construct();
}
public function myAjax(parameter='')
{
/**
* Load models, or whatever. Then echo the results, so that
* $.post gets its "data" var.
*/
}
}
I hope this helps!
I just replace :
$.post("<?= site_url('home/view/ajax') ?>", {id: msg}, function() {
$('#main').load("<?= site_url('home/view/ajax') ?>");
$('##myform1 #country').val('');
});
by
$.post('<?= site_url('home/view/ajax') ?>', options, function(data) {
$('#content').html(data);
})

Ajax method calls same function in controller but needs to load different results in different areas

I am a bit stuck with my website, currently on the new section of my site(among others) the user rolls over a thumbnail and gets the articles abstract displayed below it, and then when they click on said thumbnail the article appears on the left of the page,
The ajax works by pulling the href from the link that surronds the thumbnail image and using that as the url for the method call, the problem is that the click version will also be using the same function call, I cannot work out how to show the different content depening on what even happends, currently I have this as my code,
<?php
if(isset($content)) {
foreach($category_name as $k => $v) {
echo "<h2 class='$v[category_name]'><a href='#'>$v[category_name]</a></h2>";
echo "<div class='$v[category_name]'>";
}
$replace = array(".", "png", "gif", "jpg");
$count = 0;
foreach($content as $k=>$v) {
$count ++;
$image_name = str_replace($replace, "", $v['image_name']);
echo "<a class='contentlink' href='index.php/home/get_content_abstract/$v[content_id]'>";
echo "<img src='/media/uploads/".strtolower($v['category_name'])."/".$image_name."_thumb.png' alt='This is the picture' />";
echo "</a>";
}
echo "</div>";
//die(var_dump($content));
}
?>
<script>
$("a.contentlink").mouseover(function(){
var url = $(this).attr("href");
$.ajax ({
url: url,
type: "POST",
success : function (html) {
$('#abstract').html(html);
}
});
});
$("a.contentlink").click(function(ev) {
ev.preventDefault();
$('#main_menu').hide();
var url = $(this).attr("href");
$.ajax({
url:url,
type: "POST",
success : function (html) {
// alert(html)
$('#left-content').html(html);
}
})
});
</script>
The method that gets called is,
public function get_content_abstract() {
$this->load->model('content_model');
if($query = $this->content_model->get_content_by_id($this->uri->segment(3))) {
$data['abstract'] = $query;
}
$this->load->view('template/abstract', $data);
}
This is called by the ajax following the link /get_content_abstract/3, where 3 or any other number is the articles ID.
How can I sort so that I can use this function again, but only show that body content of the article instead of the abstract if the link is clicked and mouseovered?
You can pass a call type variable and check for it in your php code. Notice I added data to your ajax calls.
$("a.contentlink").mouseover(function(){
var url = $(this).attr("href");
$.ajax ({
url: url,
type: "POST",
data: "calltype=abstract",
success : function (html) {
$('#abstract').html(html);
}
});
});
$("a.contentlink").click(function(ev) {
ev.preventDefault();
$('#main_menu').hide();
var url = $(this).attr("href");
$.ajax({
url:url,
type: "POST",
data: "calltype=full",
success : function (html) {
// alert(html)
$('#left-content').html(html);
}
})
pass a GET variable in the url of the ajax call.
You just pass an variable to the handler via GET or POST that tells the handler which content to show. As your AJAX calls are simple, you can simplify the calls and use load(). If you can't use $_GET or $_POST, just append the data in the URL:
$("a.contentlink").mouseover(function() {
// URL becomes index.php/home/get_content_abstract/3/abstract
$('#abstract').load($(this).attr("href")+'/abstract');
});
$("a.contentlink").click(function(ev) {
$('#main_menu').hide();
// URL becomes index.php/home/get_content_abstract/3/full
$('#left-content').load($(this).attr("href")+'/full');
return false;
});
And in PHP, you can use something like this:
public function get_content_abstract() {
$this->load->model('content_model');
if($this->uri->segment(4) == 'full') {
// Load full content
} else {
// Load abstract
}
$this->load->view('template/abstract', $data);
}

Categories