Subcategories with Ajax and Codeigniter - ajax

I have select box with categories and I want to display subcategories in another select box using ajax an CodeIgniter.
This is part of my view:
<script type="text/javascript">
$(document).ready(function(){
$('#tip_category').change(function(){
msg = 'category_id='+$(this).val();
$.ajax({
type : 'POST',
url : '<?php echo base_url().'admin/tips/ajax_subcategory';?>',
data : msg
});
});
});
</script>
Category:<br/>
<select name="tip_category" id="tip_category">
<?php foreach($categories as $category): ?>
<option value="<?php echo $category['id'] ?>"><?php echo $category['name'] ?>
</option>
<?php endforeach; ?>
</select><br/>
Subcategory:<br/>
<select name="tip_subcategory"
<?php if(isset($subcategories)): ?>
<?php foreach($subcategories as $subcategory): ?>
<option value="<?php echo $subcategory['id'] ?>"><?php echo $subcategory['name'] ?>
</option>
<?php endforeach; ?>
<?php endif; ?>
</select><br/>
This is part of my controller:
public function ajax_subcategory() {
$this->load->model('tips_model');
$data['subcategories'] = $this->tips_model->get_subcategories($this->input->post('category_id'));
}
My problem is that i dont know how to send data ($data['subcategories']) back to view and display subcategories. Thx for help !

I think you are just missing the return (in whatever format you need):
return $data;

You can modify your controller to:
public function ajax_subcategory() {
$this->load->model('tips_model');
$data['subcategories'] = $this->tips_model->get_subcategories($this->input->post('category_id'));
return $this->output->set_output($data);
}

Related

How to prepopulate a cascaded drop down and attachment on validation failure

I have 2 drop downs, just for simplicity let's say they are Country / States.
<select id="country_id" name = "country_id">
<option value="">Select...</option>
<?php foreach ($countries as $country): ?>
<option value="<?php echo $country->id; ?>" <?php if (null !== set_value("country_id") && set_value("country_id") == $country->id) : echo ' selected '; ?>>$country->name;
<?php endforeach?>
</select>
<select id="state_id" name = "state_id">
<option value="">Select...</option>
</select>
<input type="file" name="attachment_id" value="" />
What I do is when the country is selected I populate the states. This I do using AJAX and ".change" and this works well
The problem I'm having is when I do form_validation and
$this->form_validation->run() == FALSE
Then I reload all controls using set_value, which does work for the first drop down (the countries) just fine, however the second drop down stays empty( as there was no ".change" triggered on the "country_id" to populate "state_id".
Similarly I am asked to re-attach the file
So what I need and is not working is after form_validation fail to
Load up second drop down with data => RESOLVED see below with .trigger event
Select the previous selection int he second drop down => ALMOST RESOLVED however only if I use alert :)
The attachment should still stay attached until form is dismissed or committed successfully => NOT RESOLVED
I feel like I need to manually trigger the data change to get (1) but in my case I have a foreach (see above) where I just add lines and if the selection is the same I simply set is as "selected" but nothing happens after.
Here is the AJAX part
<script>
$(document).ready(function(){
$("#country_id").change(function(){
$.ajax({
url:"<?php echo base_url(); ?>location/getCountries",
data: {country_id: $(this).val()},
type: "POST",
success: function(data){
$("#state_id").html(data);
$("#state_id").val(null);
}
});
});
<?php if (!empty(set_value('country_id'))) : ?>
var value = "<?php echo set_value('country_id'); ?>";
$('#country_id').val(value);
$('#country_id').trigger('change');
<?php endif; ?>
<?php if (!empty(set_value('state_id'))) : ?>
var value = "<?php echo set_value('state_id'); ?>";
//without this alert the selection doesn't work
alert(value);
$('#state_id').val(value);
$('#state_id').trigger('change');
<?php endif; ?>
});
</script>
So I am getting the values saved only if I use an alert. This seems to be an asynchronous execution where the selection of second drop down is done before it gets populated, so the last thing to do is to figure out how to wait.
Still to do the attachment part
Thanks in advance!
Add this code at the end of view page
For country dropdown
<?php if (!empty(set_value('country_id'))) : ?>
<script type="text/javascript">
var value = "<?php echo set_value('country_id'); ?>";
$('select[name="country_id"]').find('option[value="'+value+'"]').attr("selected",true);
</script>
<?php endif; ?>
For state dropdown
<?php if (!empty(set_value('state_id'))) : ?>
<script type="text/javascript">
var value = "<?php echo set_value('state_id'); ?>";
$('select[name="state_id"]').find('option[value="'+value+'"]').attr("selected",true);
</script>
<?php endif; ?>
Follow the below points
1) For select tag, use set_select(), like this
<select name="myselect">
<option value="one" <?php echo set_select('myselect', 'one', TRUE); ?> >One</option>
<option value="two" <?php echo set_select('myselect', 'two'); ?> >Two</option>
<option value="three" <?php echo set_select('myselect', 'three'); ?> >Three</option>
</select>
2) If the form validation failed, call your ajax function to set second drop down.
3) For attachment, Whatever result of the form validation, first upload the image and keep the image path in session variable. After successful form validation, save the data into database and destroy the session variable.
edited >>>
**html**
<?php
if (isset($edit) && !empty($edit)) { //while editing
$StateID = $edit['StateID'];
$CountryID = $edit['CountryID'];
} else { // while adding
$StateID = set_value('StateID');
$CountryID = set_value('CountryID');
} ?>
<div class="col-3">
<div class="form-group">
<label class="mb-0">Country</label>
<select class="form-control Country" id="country" name="CountryID" data_state_value="<?php echo $StateID; ?>" >
<option value="">Select Country</option>
<?php
foreach ($country as $row) {
$selected = ($row->id == $CountryID) ? 'selected' : '';
echo '<option value="' . $row->id . '"' . $selected . '>' . $row->country_name . '</option>';
}
?>
</select>
<span class="text-danger font9"><?php echo form_error('CountryID'); ?></span>
</div>
</div>
<div class="col-3">
<div class="form-group">
<label class="mb-0">State</label>
<select class="form-control State" id="State" name="StateID">
</select>
<span class="text-danger font9"><?php echo form_error('StateID'); ?></span>
</div>
</div>
**script**
$(document).on('change', '.Country', function () {
var country_id = $(this).val();
var state_id = $(this).attr('data_state_value');
url = $("body").attr('b_url');
$.ajax({
url: url + "Education/fetch_state",
method: "POST",
data: {
country_id: country_id,
state_id: state_id
},
success: function (res) {
var response = $.parseJSON(res);
$('#State').html('<option value="">Select State</option>' + response.view);
$('.State').trigger('change');
}
});
});
$('.Country').trigger('change');
**controller**
public function fetch_state() {
$data = array();
if (isset($_POST['country_id']) && !empty($_POST['country_id'])) {
$states = $this->Location_model->fetch_state($this->input->post('country_id')); // array of states
$view = array();
if (!empty($states)) {
foreach ($states as $val) {
$selected = (isset($_POST['state_id']) && !empty($_POST['state_id']) && $_POST['state_id'] == $val['id']) ? 'selected' : '';
$view[] = "<option value='" . $val['id'] . "'" . $selected . ">" . $val['states_name'] . "</option>";
}
$data['view'] = $view;
$data['status'] = 0;
} else {
$data['status'] = 0;
$data['view'] = '<option value="">No State Found</option>';
}
} else {
$data['status'] = 0;
$data['view'] = '<option value="">Select State</option>';
}
echo json_encode($data);
}

Display message is Not working for out of stock products

please visit link1 , you can see there is option to find shipping is available or not for particular zip code : image1
here shipping charges are working for instock products but not for out-of -stock products.
Form.phtml
app/design/frontend/default/default/template/webdevlopers/productpageshipping/estimate/form.phtml
<?php if ($this->isFieldVisible('postcode')): ?>
<li class="item">
<label for="search"<?php if ($this->isFieldRequired('postcode')):?> class="required" <?php endif;?>>
<?php if ($this->isFieldRequired('postcode')):?>
<em>*</em>
<?php endif;?>
<?php echo Mage::helper('webdevlopers_productpageshipping')->__('') ?>
</label>
<div class="search">
<input placeholder="Enter your PIN Code"
class="input-text validate-postcode<?php if ($this->isFieldRequired('postcode')):?> required-entry<?php endif;?>"
type="text" id="estimate_postcode"
name="estimate[postcode]"
value="<?php echo $this->htmlEscape($this->getFieldValue('postcode')) ?>"
onkeydown="if (event.keyCode == 13) { return false;}" />
</div>
</li>
<?php endif; ?>
Script
<script type="text/javascript">
var $ = jQuery.noConflict();
(function($) {
$(document).ready(function(){
$('#estimate_postcode').keydown(function(e){
var items = $$(['.shipping-estimation-form input',
'.shipping-estimation-form select',
'#product_addtocart_form input',
'#product_addtocart_form select']);
var estimationUrl = '<?php echo $this->jsQuoteEscape($this->getEstimateUrl());?>';
var parameters = Form.serializeElements(items, true);
console.log("zipcode onkeypress worked");
if (!e) e = window.event;
var keyCode = e.keyCode || e.which;
if (keyCode == '13'){
//disable default enter action
e.preventDefault();
console.log("Enter button was pressed");
$('#shipping-estimate-loading-message').show();
$('#shipping-estimate-results').hide();
new Ajax.Updater('shipping-estimate-results', estimationUrl, {
parameters: parameters,
onComplete: function() {
console.log("ajax updater worked");
$('#shipping-estimate-loading-message').hide();
$('#shipping-estimate-results').show();
$('#unique_id').hide();
//$('unique_id').hide();
$('estimate_postcode').val()
}
});
};
});
});
}) ( jQuery );
function estimateProductShipping()
{
var estimationUrl = '<?php echo $this->jsQuoteEscape($this->getEstimateUrl());?>';
var items = $$(['.shipping-estimation-form input',
'.shipping-estimation-form select',
'#product_addtocart_form input',
'#product_addtocart_form select']);
var validationResult = true;
// Check the valid input
if (!items.map(Validation.validate).all()) {
return;
}
var parameters = Form.serializeElements(items, true);
$('shipping-estimate-loading-message').show();
$('shipping-estimate-results').hide();
new Ajax.Updater('shipping-estimate-results', estimationUrl, {
parameters: parameters,
onComplete: function() {
console.log("ajax updater worked");
$('shipping-estimate-loading-message').hide();
$('shipping-estimate-results').show();
// $('#unique_id').hide();
$('unique_id').hide();
$('estimate_postcode').val()
}
});
}
//]]>
</script>
complete code of the file : https://gist.github.com/anonymous/ebe868508b2c21e9c032
result.phtml
app/design/frontend/default/default/template/webdevlopers/productpageshipping/estimate/result.phtml
<div class="block block-shipping-estimate block-shipping-results">
<div class="block-title">
<strong><span>
<?php echo Mage::helper('webdevlopers_productpageshipping')->getShiptitle(); ?>
</span></strong>
</div>
<div class="block-content">
<?php if ($this->getResult()):?>
<dl>
<?php foreach ($this->getResult() as $code => $_rates): ?>
<dt><?php echo $this->getCarrierName($code) ?></dt>
<dd>
<ul>
<?php foreach ($_rates as $_rate): ?>
<li<?php if ($_rate->getErrorMessage()) echo ' class="error-msg"';?>>
<?php if ($_rate->getErrorMessage()): ?>
<?php echo $_rate->getErrorMessage() ?>
<?php else: ?>
<?php
// echo $_rate->getMethodTitle()
?>
<?php $_excl = $this->getShippingPrice($_rate->getPrice(), $this->helper('tax')->displayShippingPriceIncludingTax()); ?>
<?php $_incl = $this->getShippingPrice($_rate->getPrice(), true); ?>
<!-- sat -->
<p>
<?php echo "Shipping is available";?>
</p>
<p class="vship1">
<?php echo "Selling Price + " . str_replace('.00','',$_excl) . " Delivery ";?>
</p>
<!-- sat -->
<?php if ($this->helper('tax')->displayShippingBothPrices() && $_incl != $_excl): ?>
(<?php echo Mage::helper('webdevlopers_productpageshipping')->__('Incl. Tax'); ?> <?php echo $_incl; ?>)
<?php endif; ?>
<?php endif ?>
</li>
<?php endforeach; ?>
</ul>
</dd>
<?php endforeach; ?>
</dl>
<?php else: ?>
<?php //echo $this->getMessagesBlock()->toHtml(); ?>
<?php echo Mage::helper('webdevlopers_productpageshipping')->getResult(); ?>
<?php endif;?>
</div>
</div>
app/code/community/webdevolopers/productpageshiping/Block/estimate/ Result.php
<?php
class WebDevlopers_ProductPageShipping_Block_Estimate_Result extends WebDevlopers_ProductPageShipping_Block_Estimate_Abstract
{
public function getResult()
{
return $this->getEstimate()->getResult();
}
public function hasResult()
{
return $this->getResult() !== null;
}
public function getCarrierName($code)
{
$carrier = Mage::getSingleton('shipping/config')->getCarrierInstance($code);
if ($carrier) {
return $carrier->getConfigData('title');
}
return null;
}
public function getShippingPrice($price, $flag)
{
return $this->formatPrice(
$this->helper('tax')->getShippingPrice(
$price,
$flag,
$this->getEstimate()
->getQuote()
->getShippingAddress()
)
);
}
public function formatPrice($price)
{
return $this->getEstimate()
->getQuote()
->getStore()
->convertPrice($price, true);
}
}
changing the settings in System > Config > Inventory
Easiest way to do this is select all products you want to allow to be backordered, then select Update attributes from the actions drop down and click submit. then shipping problem will not be problem.

create a select dropdown from database in codeigniter

I am new with codeigniter.I want to make a select dorpdown that gets its value and title from database.I tried some codes but it did not work.There are my codes:
Model
function get_sec_info(){
$records=$this->db->query('SELECT sec_id,name FROM section');
if($records->num_rows() > 0)
return $records->result();}
Controller
function sec_ifo(){
$data['rec']=$this->mymodel->get_sec_info();
$this->load->view('article',$data);}
View
<select name="section">
<?php foreach($rec as $row) {?>
<option value="<?php echo $row->sec_id?>"><?php echo $row->name ?></option>"
<?php } ?>
It does not show any error and any option to show
In the controller you set "red" $data['red'] and in the view you access "rec" foreach($rec
Model:
function get_sec_info(){
$this->db->select('sec_id,name');
$records = $this->db->get('section');
return $records->result();
}
Controller:
function sec_ifo(){
$this->load->model('mymodel');
$this->data['red'] = $this->mymodel->get_sec_info();
$this->load->view('article',$this->data);
}
View:
<select name="section">
<?php foreach($red as $row) { ?>
<option value="<?php echo $row->sec_id; ?>"><?php echo $row->name; ?></option>
<?php } ?>
Model
public function getClasse() {
$query(`enter code here`);
$result = $this->db->query($query)->result_array();
foreach ($result as $key => $rows) {
$resultado[] = $rows['DescricaoClasse'];
}
return $resultado;
}
Controller:
public function getClasse() {
$this->load->model('Decisao_monocratica_model');
return $this->Decisao_monocratica_model->getClasse();
}
View
<select id="ClasseProcesso" class="input-xlarge" name="classeProcesso">
<option value="0">Todos os Tipos</option>
<? foreach ($classeProcesso as $key => $classe) { ?>
<option value="<? echo $classe ?>"><? echo $classe ?></option>
<? } ?>
</select>

Strange replace on magento URL

For some reason, only on view-mode icons on the product list, the "?" of the urls are replaced to "#21". Ex.: "#%21mode=list"
Somebody can help me?
Some code:
app/design/frontend/default/themename/template/catalog/product/list/toolbar.phtml
<?php if( $this->isEnabledViewSwitcher() ): ?>
<p class="view-mode">
<?php $_modes = $this->getModes(); ?>
<?php if($_modes && count($_modes)>1): ?>
<label><?php echo $this->__('View as') ?>:</label>
<?php foreach ($this->getModes() as $_code=>$_label): ?>
<?php if($this->isModeActive($_code)): ?>
<strong title="<?php echo $_label ?>" class="<?php echo strtolower($_code); ?>"><?php echo $_label ?></strong>
<?php else: ?>
<?php echo $_label ?>
<?php endif; ?>
<?php endforeach; ?>
<?php endif; ?>
</p>
<?php endif; ?>
app/code//core/Mage/Catalog/Block/Product/List/Toolbar.php
public function getModeUrl($mode)
{
return $this->getPagerUrl( array($this->getModeVarName()=>$mode, $this->getPageVarName() => null) );
}
and...
public function getPagerUrl($params=array())
{
$urlParams = array();
$urlParams['_current'] = true;
$urlParams['_escape'] = true; // I already tried set false, but didn't helps
$urlParams['_use_rewrite'] = true;
$urlParams['_query'] = $params;
return $this->getUrl('*/*/*', $urlParams); // I also tried not use the getUrl and concat the querystring, strangely the replace still happends...
}
I couldn't find the problem, but I make a dirt solution:
<?php echo str_replace('#%21', '&', $this->getModeUrl($_code)); ?>
I wish somebody find a better solution :)

can't use multiple ajaxLink for loading CJuiDialog widget

I have a problem when using multiple ajaxLink for loading CJuiDialog widget in yii. I'm using multiple dropdowns, each dropdown's value determine next dropdown.
Here is my code for viewing first dropdown and a link to create new item using Cdialog widget.
<?php $cs = Yii::app()->getClientScript();
$cs->registerCoreScript("jquery");
?>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'enableAjaxValidation'=>false,
)); ?>
<div class="row">
<?php
echo $form->labelEx($model,'uname'); ?>
<?php echo $form->dropDownList($model,'uname',$model- >getUniversityList(),array('onchange'=>'getSchemes(this.value)','empty'=>'Select university')); ?>
<?php echo $form->error($model,'uname'); ?>
<?php //create university dialoge box
if(!Yii::app()->user->isGuest)
{
echo CHtml::ajaxLink('create new university',array('university/dialoge'),array(
'success'=>'js:function(data){
$("#createUniversity").dialog("open");
document.getElementById("create_university").innerHTML=data;
}'));
$this->beginWidget('zii.widgets.jui.CJuiDialog',array(
'id'=>'createUniversity',
'options'=>array(
'title'=>'Create University',
'autoOpen'=>false,
'modal'=>'true',
'width'=>'auto',
'height'=>'auto',
),
));
echo "<div id='create_university'></div>";
$this->endWidget('zii.widgets.jui.CJuiDialog');
}
?>
<div id="scheme">
</div>
</div>
<?php $this->endWidget(); ?>
</div>
<input type="hidden" id="url" value="<?php echo $this->createUrl('scheme/test'); ?>">
this works pretty good.
here is the javascript code for loading next dropdown in the same view file
<script type="text/javascript">
function getSchemes(uid)
{
if(uid==""){
document.getElementById("scheme").innerHTML='';
return;
}
jQuery(function($){
var url=document.getElementById("url").value;
$.post(url, { uid:uid },
function(data){
document.getElementById("scheme").innerHTML=data;
document.getElementById("scheme_link").style.display="block";
});
});
}
The scheme drop down is loaded as the scheme view code is
<?php $cs = Yii::app()->getClientScript();
$cs->registerCoreScript("jquery");
?>
<?php
echo "<div class=".'label'."><label for=".'sch'.">Scheme</label></div>";
echo "<select id=".'sch'." onchange='getDepartments(this.value);'>";
echo "<option value=".''.">"."Select Scheme</option>";
foreach($schemes as $s)
{
echo "<option value='".$s->schemeid."' >".$s->scheme_name."</option>";
}
echo "</select>";
?>
<?php
if(!Yii::app()->user->isGuest)
{
echo CHtml::ajaxLink('create new Scheme',array('scheme/dialoge','id'=>5),array(
'success'=>'js:function(data1){
$("#createScheme").dialog("open");
document.getElementById("create_scheme").innerHTML=data;
}'));?>
<?php
$this->beginWidget('zii.widgets.jui.CJuiDialog',array(
'id'=>'createScheme',
'options'=>array(
'title'=>'Create Scheme',
'autoOpen'=>false,
'modal'=>'true',
'width'=>'auto',
'height'=>'auto',
),
));
echo "<div id='create_scheme'></div>";
$this->endWidget('zii.widgets.jui.CJuiDialog');
}
?>
<div id="department">
</div>
<input type="hidden" id="urldepart" value="<?php echo $this->createUrl('department/test'); ?> ">
the second ajaxLink is shown as create new scheme but on clicking the link it shows the old create university dialog box instead of create scheme.
The simplest solution for this is to create the ID of the element that is causing problems as random.
Try adding:
'id' => 'some-element'.uniqid() // avoid mutliple ajax request because of using live
in the $htmlOptions array of ajaxLink

Resources