call function after view has loaded in CodeIgniter - codeigniter

i have this code.
function index(){
$this->load->helper('url');
$this->load->view('EIM/home');
$this->loadGraphs();
}
but it executes loadGraphs first. I really have no idea why. Please help me. I'm having a hard time fixing my codes. thanks :)
here is my loadGraphs function:
`function loadGraphs(){
$this->load->helper('url');
$ctr=0;
$base_url = base_url();
$xml=new DOMDocument;
$xml->load("".$base_url."assets/EIM/xml/defaultChart.xml");
$module_names=$xml->getElementsByTagName("name");
$len_modules=$module_names->length;
$ctr_module=0;
while($ctr_moduleitem($ctr_module)->getElementsByTagName("report");
$len_reports=$reports->length;
$ctr_report=0;
while($ctr_reportitem($ctr_module)->getAttribute("value");
$title=$reports->item($ctr_report)->getElementsByTagName("title")->item(0)->nodeValue;
$dashboard_selected=$reports->item($ctr_report)->getAttribute("id");
if($dashboard_selected=="dashboard"){
echo "
$title
$module";
?>
var parameters=eval(getArray($title,$module));?>)
item($ctr_report)->getElementsByTagName("charts")->item(0)->getAttribute("value");
$defaultChart=$reports->item($ctr_report)->getElementsByTagName("charts")->item(0)->getAttribute("value");
echo "$defaultChart";
$charts=$reports->item($ctr_report)->getElementsByTagName("charts")->item(0)->getElementsByTagName("chart");
$len_charts=$charts->length;
$ctr_chart=0;
while($ctr_chartitem($ctr_chart)->nodeValue;
echo "
";
$ctr_chart++;
}
echo"
<input type='submit' value='Set Chart as Default' onClick='set_default_chart('chart$ctr',$ctr_module,$ctr_report)'/>
";
echo "
<button class='btn btn-box-right' data-toggle='collapse' data-target='#container".$ctr."'>
<i class='icon-reorder'></i>
</button>
</div>
<div class='box-content box-list collapse in'>
<div id='container".$ctr."' style='min-width: 310px; height: 400px; margin: 0 auto'></div>
</div>
</div>
</div>
";
$ctr++;
}
$ctr_report++;
}
$ctr_module++;
}
echo "<label id='containers' value='$ctr'></label></div>";
}`
its kinda long but what it does is that it makes the containers ready and my java script is there to load and completely show the graphs. its in the document.ready function. it is possible that it prioritizes the codes that have function before loading the view?

You could try loading that results of the loadGraphs() function via AJAX from the view once it loads? So basically remove that call after the $this->load->view('EIM/home'), and in that same view, in documentReady, use the simple jQuery.Get function to fetch that code you need in the view. That will load if after the view 100%.
http://api.jquery.com/jquery.get/
Not sure if your flow is the best approach, but this should work.
Hope it helps! :)

Related

How do I call the function to check in a view?

How do I check if my database has more than 9 entries, and if it has, I can advance to the next page.
Currently I have this code, but I don't know how to call that in my view:
Here in the controller I have already called the checklogin and see if it has more than 9 entries.
Controller:
function quizzes(){
$this->load->model('Quiz_Model');
$data['categorys'] = $this->Quiz_Model->SearchAllCategorys();
$this->load->view('headerLogged');
$this->load->view('quizzes', $data);
$this->load->view('footer');
}
function proses_quiz($id_category){
$this->load->view('headerLogged');
$checkquiz=$this->Quiz_Model->checkquiz($id_category);
if($checkquiz > 9){
redirect('User_Ctr/quiz/').$id_category;
}else{
$data['error_quiz']="MEH";
$this->load->view('quizzes', $data);
}
$this->load->view('footer');
}
And here it's just the code to make the count:
Model:
public function checkquiz($id_category){
$this->db->select('id_question, COUNT(id_question) as total');
$this->db->from('questions');
$this->db->where('id_category', $id_category);
$result = $this->db->get();
return $result->result();
}
View:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<div class="container">
<h1 class="my-4 text-center text-lg-left">Quizzes</h1>
<div class="row text-center text-lg-left">
<?php foreach($categorys as $cat): ?>
<div class="col-lg-3 col-md-4 col-xs-6" >
<a href="<?php echo 'quiz/'.$cat->id_category ?>" class="d-block mb-4 h-100" >
<img class="img-fluid img-thumbnail" src="<?php echo $cat->img_category ?>" alt="" style="height: 125px; width: 400px">
<?php
if(isset($error_quiz)){
echo $error_quiz;
}
?>
</a>
</div>
<?php endforeach ?>
</div>
</div>
I will answer you question generally.
If you want to call something in the view you have many options like you have the variable already calculated in advance and already passed it to view waiting for a call, or you can click on a link that maybe reload the current view with the new variable done, or you can use ajax to go get the variable from the controller without reloading.
So if the variable has fixed value that doesn't depend on your action, go with the first option or else chose one of the others.

CodeIgniter flashdata [flash:old:message] being displayed

I'm using CodeIgniter on OpenShift.
In my controller I'm using:
$this->session->set_flashdata('message', 'message X');
$this->load->view('viewpage');
In my view I'm using:
print_r ($this->session->userdata);
echo $this->session->flashdata('message');
Here are my observations:
first time through the controller/load view, I see nothing echoed with the
$this->session->flashdata('message');
I see this with the print_r:
[flash:new:message]=>message 1
second time through the controller/load view, I see "message 1" being echoed
I see this with the print_r:
[flash:old:message] =>message 1[flash:new:message]=>message 2
So what appears to be happening is that [flash:old:message] is being displayed instead of [flash:new:message]. If [flash:old:message] isn't set, then nothing is displayed.
Please help.
Cheers,
Mike
when you set a value in a flash data, you need to make a view refresh like:
controller.php
function do_somthing(){
$this->session->set_flashdata('index', 'text message');
redirect('controller/view', 'refresh');
}
controller/view.php
<div>
<?= (isset($this->session->flashdata('index'))) ? $this->session->flashdata('index') : ''?>
</div>
Flashdata is designed to be used moving from 1 page to another (redirects), you typically use it after a post, the return a success/failure message.
the reason for this:
[flash:old:message] =>message 1[flash:new:message]=>message 2
occurring is because flashdata is retained for 1 additional page load (so you can use $this->session->keep_flashdata() if required... as you are triggering flashdata by refreshing the page to generate these results its confusing things and not designed for use this way..
This really seems to be an issue occurring due to the way you are using flashdata than it displaying the incorrect data.
A working example of using flashdata is below (even without a redirect)
controller:
public function index()
{
if (!$this->input->post()) {
$this->load->view('playland/index');
}else{
if ($this->input->post('submit') == "submit") {
$data['firstname'] = $this->input->post('firstname');
$data['lastname'] = $this->input->post('lastname');
$this->session->set_flashdata('test', 'data posted');
$this->load->view('playland/retrieve', $data);
}
}
}
index view:
<html>
<body>
<?php print_r($this->session->userdata)?>
<form method="post" action="playland">
First name:<br>
<input type="text" name="firstname"><br>
Last name:<br>
<input type="text" name="lastname"><br>
<input type="submit" value="submit" name="submit">
</form>
</body>
</html>
retrieve view:
<html>
<body>
<?php echo $this->session->flashdata('test') ?><br>
<p>
First Name:<br>
<?php echo isset($firstname) ? $firstname : '';?><br>
Last Name:<br>
<?php echo isset($lastname) ? $lastname : '';?><br>
</p>
Click to refresh the page
Return to original page
</body>
</html>

Updating Values Using Ajax in Yii

This is my first ever post....
I'm working on a shopping website using Yii-Booster but I'm currently stumped! Basically what I'm trying to achieve is that when a user adds a product to the cart, a modal displays showing an acknowledgement message and then the div with the shopping cart is updated to reflect the new total.
Really simple, innit?? I've spent the entire day trying to get it to work. Any help you can offer would be greatly appreciated.
Oh yeah... one more thing, the dropdown menu in the navbar stops working after almost any sort of AJAX action(loading modals, etc). I'm guessing its caused by a conflict somewhere but I'm completely lost in Jquery/Ajax stuff.
Thanks for the replies. Here's my code:
StoreController:
// action allowing a product to be added to the shopping cart
public function actionAddToCart($id)
{
//fetch item
$item = Item::model()->findByPk($id);
//if item is in cart
if(Yii::app()->shoppingCart->contains($id))
{
//Yii::app()->clientScript->scriptMap['jquery.js'] = true;
//$this->renderPartial('_addToCart',array('data'=>$data),false,true);
echo CJSON::encode(
array(
//'total'=>'Your Cart (N'.number_format(Yii::app()->shoppingCart->getCost()).')',
'addCart'=>$this->renderPartial('_inCart',array('item'=>$item),true),
)
);
//CHtml::ajax();
}
else
{
Yii::app()->shoppingCart->put($item);
//Yii::app()->clientScript->scriptMap['jquery.js'] = true;
//$this->renderPartial('_addToCart',array('data'=>$data),false,true);
//$this->renderPartial('_addToCart',array('item'=>$item),false,true);
echo CJSON::encode(
array(
'total'=>'Your Cart (N'.number_format(Yii::app()->shoppingCart->getCost()).')',
'addCart'=>$this->renderPartial('_addToCart',array('item'=>$item),true),
)
);
}
}
_display (partialview showing the product)
<div style="float: left; display: inline; margin-right: 30px; margin-top: 20px;">
<img style="border: 1px solid black;" src="<?php echo Yii::app()->baseUrl; ?>/images/products/thumbs/<?php echo $data->image; ?>" />
<div style="font-size: 14px; margin-top: 3px;">
Name: <?php echo CHtml::ajaxLink($data->name, array("view", "id"=>$data->id), array('update'=>'#viewdetailsDiv',)); //array(), array('data-toggle'=>'modal','data-target'=>"#".$data->id)); ?><br/>
Category: <?=$data->category->category?><br/>
Gender: <?=$data->gender?><br/>
Price: <?php echo "N".number_format($data->price);?><br/>
<?php //echo CHtml::ajaxLink("Add to Cart", array("addtocart", "id"=>$data->id), array( 'update'=>'#addtocartDiv',)); ?>
<?php echo CHtml::ajaxLink("Add to Cart", array("addtocart", "id"=>$data->id), array( 'type'=>'POST', 'dataType'=>'json',
'success'=>'function(data){
$("#Cart").html(data.total);
}'
)
); ?>
</div>
Here's the code for the view containing the modal
<?php $this->beginWidget('bootstrap.widgets.TbModal', array('id'=>'myModal', 'autoOpen'=>true, 'htmlOptions'=>array('style'=>'margin-top: 2px;'))); ?>
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h4>Your Cart has been updated</h4>
</div>
<div class="modal-body">
<p>The item, <strong><?php echo $item->name; ?></strong> (<?php echo $item->category->category; ?>), has been added to your shopping cart.</p>
</div>
<div class="modal-footer">
<?php $this->widget('bootstrap.widgets.TbButton', array(
'type'=>'primary',
'label'=>'Close',
'url'=>'#',
'htmlOptions'=>array('data-dismiss'=>'modal'),
)); ?>
</div>
<?php $this->endWidget(); ?>
I can't tell you the perfect solution but can give you a suggestion regarding Yii that can solve your problem.
Always load all the jquery or js files used in first request. Never load again any js file in any ajax request, It will a lot of problems.
You can achieve it in simple way
if(Yii::app()->request->isAjaxRequest){
Yii::app()->clientScript->scriptMap['jquery.js'] = true;
}

Ajax CodeIgniter form submit hide and show new view

I'm a newbie to ajax and trying to integrate it in to my CodeIgniter app. Basically, when the form is successful I would like the original template to be hidden and the new one shown? It currently displays both, how could I amend my code? Thanks in advance!
I have tried adding a redirect to my controller with no such luck :(
view:
$('#submit').click(function(){
$.post("<?php echo base_url(); ?>part-two",
$("form").serialize(),
function(result){
$("#error_message").html(result);
}, "html"
);
});
controller:
if($this->form_validation->run() == FALSE){
echo validation_errors();
} else {
echo "success";
$data['content'] = "part_two";
$this->load->view('template', $data);
}
OK, I think that I know what you want...
View html markup:
<div class="container">
<form id="form">
...
</form>
<div class="error_message">
</div>
</div>
Script:
$('#submit').click(function(){
$.post("<?php echo base_url(); ?>part-two",
$("form").serialize(),
function(result){
// clear the content and assing the result
$("#form").remove();
$("#error_message").html(result);
}, "html"
);
});
I cant help you so much. Would you please use firebug to see received data of post request ?
Since both are displaying so i think post request is okay. Problem is in your view file.

prototype ajax updater div with different buttons

i'm learning it, but i cant find what's wrong in this!
i want the div2 to get data from the form in div1, called formulario.
i would like to know which item is selected and which button was clicked.
main html file:
<script src="utils/Scripts/prototype.js" type="text/javascript"></script>
<script type="text/javascript">
function sendf(formul, divi, php)
{
var params = Form.serialize($(formul));
new Ajax.Updater(divi, php, {method: 'post', parameters: params, asynchronous:true});
}
</script>
</head>
<body>
<div id="div1">
contenido div1
<form id="formulario" method="POST">
<select size="3" id="lista" onchange="sendf('formulario', 'div2', 'prodiv1.php');">
<option>elemento 1</option>
<option>elemento 2</option>
<option>elemento 3</option>
</select>
<input type="button" id="b1" value="bot1" onclick="sendf('formulario', 'div2', 'prodiv1.php');" />
<input type="button" id="b2" value="bot2" onclick="sendf('formulario', 'div2', 'prodiv1.php');" />
</form>
<div id="div2" style="background: blue;">
contenido div2
</div>
</div>
</body>
</html>
the php file, prodiv1.php:
<?
echo 'exec: prodiv1.php<br>';
print_r($_POST);
echo serialize($_POST);
if (isset($_POST))
{
foreach ($_POST as $key=>$value)
{
echo $key.'=>'.$value."<br>";
}
}
echo "select: ".$_POST['lista'];
if (isset($_POST['b1'])) {echo 'click: boton1';} else {echo 'click: boton2';}
?>
i've tried a lot of things, and seen that it could be done with event observers, httprequests and such, but what i need is quite easy, and probably there's an elegant way to solve it...
i thank in advance any help!
have a nice day.
guillem
if you dont need to actually process the form contents in some way then you have no need to use Ajax to pass to a PHP script. Depending on what exactly you wanted to display in div 2 you could do something as simple as this:
function sendf()
{
var listvar = $('lista').value;
$('div2').update('select menu value was ' + listvar);
}
This is obviously missing quite a lot of detail and can be massively improved but it should highlight the fact that AJAX is not required.
Edit Looking at the rest of the code you have posted, is AJAX really required for this? surely you are just updating the existing page with data already present on the page, the server has no real part to play in this?
Sorry to dive into jQuery again, but this should allow you to get the values into "div2" without an ajax request.
$(document).ready(function() {
$("input").click(function(e) {
$("#div2").html($(this).attr("id")+" clicked<br />");
updateList();
});
});
function updateList() {
$("#div2").append($("#lista").val() + " selected");
}
In plain English this code says "if an input element is clicked, update the value of div2 with the input variables id, and append the selected value from the list to the result". Hopefully that makes sense to you :)
If you need an easy, elegant way to solve this with AJAX, use the jQuery library's ajax and post methods. For more information take a look here, it will significantly cut down on the size and complexity of your code.

Resources