I am trying to create dynamic dropdown of category and on selection of this category sub-category dropdown should appear. I have done this using OOP PHP but really having tought time with codeigniter.
Firstly I have created this category dropdown
<?php
$js =' onChange="callAjaxFunction(this.value)"';
echo form_dropdown('category', $categories, null, $js); ?>
Javascript to show sub-category
<script>
// JavaScript Document
var enableCache = false;
var jsCache = new Array();
var AjaxObjects = new Array(new sack(),new sack());
function ShowContent(divId,ajaxIndex,url)
{
document.getElementById(divId).innerHTML = AjaxObjects[ajaxIndex].response;
if(enableCache){
jsCache[url] = AjaxObjects[ajaxIndex].response;
}
AjaxObjects[ajaxIndex] = false;
document.getElementById("ajax_container").innerHTML = '';
}
function ShiftChanger(divId,url,id) {
//to show the div
document.getElementById(divId).innerHTML="";
if(enableCache && jsCache[url]){
document.getElementById(divId).innerHTML = jsCache[url];
return;
}
var ajaxIndex = AjaxObjects.length;
AjaxObjects[ajaxIndex] = new sack();
AjaxObjects[ajaxIndex].requestFile = url+"?id="+id;
document.getElementById("ajax_container").innerHTML = '<img src=ajax_loader.gif hspace=10 vspace=10 />'; AjaxObjects[ajaxIndex].onCompletion = function(){ ShowContent(divId,ajaxIndex,url+"?id="+id);};
AjaxObjects[ajaxIndex].runAJAX();
}
function callAjaxFunction(value)
{
ShiftChanger('shiftcontainer','ajax_category.php',value);
}
</script>
But this is not working. As you can see ajax_category.php is not being able to pass. I think it should be done with controller, I had tried that also but nothing seems as working. I am really stuck with this. Please anyone with little help. Really getting depressed with it :(.
Related
How do I get the SKU no to change once the the product attribute of an item is selected.
enter image description here
To get sku of selected associated product on configurable product page, please paste the following code in app/design/frontend///template/catalog/product/view/type/options/configurable.phtml in side the script:
spConfig.getIdOfSelectedProduct = function()
{
var existingProducts = new Object();
for(var i=this.settings.length-1;i>=0;i--)
{
var selected = this.settings[i].options[this.settings[i].selectedIndex];
if(selected.config)
{
for(var iproducts=0;iproducts<selected.config.products.length;iproducts++)
{
var usedAsKey = selected.config.products[iproducts]+"";
if(existingProducts[usedAsKey]==undefined)
{
existingProducts[usedAsKey]=1;
}
else
{
existingProducts[usedAsKey]=existingProducts[usedAsKey]+1;
}
}
}
}
for (var keyValue in existingProducts)
{
for ( var keyValueInner in existingProducts)
{
if(Number(existingProducts[keyValueInner])<Number(existingProducts[keyValue]))
{
delete existingProducts[keyValueInner];
}
}
}
var sizeOfExistingProducts=0;
var currentSimpleProductId = "";
for ( var keyValue in existingProducts)
{
currentSimpleProductId = keyValue;
sizeOfExistingProducts=sizeOfExistingProducts+1
}
if(sizeOfExistingProducts==1)
{
alert("Selected product is: "+currentSimpleProductId)
}
}
Now add onchange event to your dropdown in same page:
onchange="spConfig.getIdOfSelectedProduct()"
First code will alert simple associated product id. You can use it in below code now.
jQuery.ajax({
type: "POST",
url: "<?php echo $this->getBaseUrl()?><module_front_name>/<controller_name>/<action_name>/",
data:"id="+currentSimpleProductId,
success: function(msg)
{
alert(msg);
//var data = JSON.parse(msg);
//alert(data.id);
}
});
Now, go to controller file which you have used above and create a new action with name Action and put below code in it:
public function <action_name>Action()
{
$productId = $_REQUEST['id'];
/*$productId is your selected product id. do what ever you want to do here.*/
$product = Mage::getModel('catalog/product')->load($productId);
$productsku = $product->getSku();
$arraygroup = array("sku"=>$productsku);
echo json_encode($arraygroup);
}
Now you can use this information in your phtml file to show sku.
Please let me know if anything is unclear.
Go to Magento admin
In catalog > Manage attribues find sku and look for similar to "Visible on Product View Page on Front-end"
This should remove the sku from product page
Find the configurable product template and insert where you would like to have your SKU
echo $product->getSku()
I have 2 functions in "events" (index, event_ajax)controller in my cakephp(2.5) web site. I'm trying to load HTML block to 'index.ctp' page by calling to 'event_ajax' function using ajax. When I call to this function it shows nothing. Look at 'net' tab in firebug it shows internal server error and 'net'->'Response' tab I can see whole layout is loaded.
I'm little confuse about in this scenario, can any one give a little explanation for following questions??? thanks in advance :)
Is it possible to call actions in same controller using ajax function ??
How 'Response' tab shows layout when '$this->layout' is set to NULL ??
when type url 'example.com/events/event_ajax', output data still '$this->autoRender=false'. how can this happen ??
this is my 'event_ajax' action.
public function event_ajax($x=1) {
$this->layout = NULL;
$this->autoRender = false ;
$contName = $this->Page->conName($x);
$latestContEvents = $this->Page->latestContEvent($x);
$internal = '';
if (!empty($latestContEvents)){
foreach ($latestContEvents AS $latestContEvent){
$internal .= '<li class="pull-left"> <div class="content-wrapper">'..... //do something
}
else {
$internal = '<p> No events found for this continent</p>';
}
$ContEvents = '<div class="carousel events-location-carousel">'.$internal.'</div> ';
return $ContEvents;
// return json_encode($ContEvents);
}
Try with
$this->layout = 'ajax';
Can someone help me with ajax pagination please, i'm on it 2 days already and can't figure it out. I have Load More style pagination, this is the code, preety classic(down below).
Everything works as planing except when the placeholder reaches page 10. Then, hell break loose and nothing is loading anymore. The button still works untill maxpages is reached and so the button gets removed, but nothing happens with more than 10 placeholders. The website i'm currently using this scriptand the place you can test yourself is this: http://filmhdonline.com/category/toate-filmele/
I would appreciate someone having an ideea what i'm talking about. Thanks in advance.
jQuery(document).ready(function() {
// The number of the next page to load (/page/x/).
var pageNum = parseInt(pbd_alp.startPage);
// The maximum number of pages the current query can return.
var max = parseInt(pbd_alp.maxPages);
// The link of the next page of posts.
var nextLink = pbd_alp.nextLink; pageNum++;
//Load more videos translation
var more = pbd_alp.more;
//Loading videos translation
var loading = pbd_alp.loading;
/**
* Replace the traditional navigation with our own,
* but only if there is at least one page of new posts to load.
*/
if(pageNum <= max) {
// Remove the traditional navigation.
jQuery('.pagination').remove();
// Insert the "More Posts" link.
if( jQuery('#content').find('ul.listing-videos').length == 1 ){
jQuery('#content ul.listing-videos').append('<li class="more-posts pbd-alp-placeholder-' + pageNum + '"></li>');
jQuery('#content').append('<p id="pbd-alp-load-posts" class="pagination">' + more + '</p>');
}
}
/**
* Load new posts when the link is clicked.
*/
jQuery('#pbd-alp-load-posts a').click(function() {
// Are there more posts to load?
if(pageNum <= max) {
// Show that we're working.
jQuery(this).text(loading);
jQuery('.pbd-alp-placeholder-'+ pageNum).load(nextLink + ' #content ul.listing-videos li',
function() {
//jQuery('.pbd-alp-placeholder-'+ pageNum).children('li').unwrap();
console.log(pageNum);
jQuery(this).children().hide();
$newContent = jQuery(this).children().unwrap();
$newContent.fadeIn('fast');
// Update page number and nextLink.
pageNum++;
nextLink = nextLink.replace(/\/page\/[0-9]?/, '/page/'+ pageNum);
**// Add a new placeholder, for when user clicks again.
jQuery('#content ul.listing-videos').append('<li class="more-posts pbd-alp-placeholder-'+ pageNum +'"></li>');**
// Update the button message.
if(pageNum <= max) {
jQuery('#pbd-alp-load-posts a').text('Vezi mai multe');
} else {
jQuery('#pbd-alp-load-posts a').remove();
}
}
);
} else {
jQuery('#pbd-alp-load-posts a').append('.');
}
return false;
});
});
For ajax pagination in wordpress, You can use the plugin like https://wordpress.org/plugins/wp-pagenavi/.
OR
<div id="content">
<?php
$new_query = new WP_Query();
$new_query->query('post_type=post&showposts=1'.'&paged='.$paged);
?>
<?php while ($new_query->have_posts()) : $new_query->the_post(); ?>
<?php the_title(); ?>
<?php endwhile; ?>
<div id="pagination">
<?php next_posts_link('« Older Entries', $new_query->max_num_pages) ?>
<?php previous_posts_link('Newer Entries »') ?>
</div>
</div><!-- #content -->
<script>
jQuery(function($) {
$('#content').on('click', '#pagination a', function(e){
e.preventDefault();
var link = $(this).attr('href');
$('#content').fadeOut(500, function(){
$(this).load(link + ' #content', function() {
$(this).fadeIn(500);
});
});
});
});
</script>
I Have the same problem.
If it still happening, replace:
nextLink = nextLink.replace(/\/page\/[0-9]?/, '/page/'+ pageNum);
to
nextLink = nextLink.replace(/\/page\/[0-9]*/, '/page/'+ pageNum);
Problem in wrong regex [0-9]? match only single number from 1 to 9. From 10 it takes only 1. Instead [0-9]* match from 0 to infinity. So, it breaks after 9 (form 0 to 9), because next 10 and it's take fore use only 1.
I'm trying to move some AJAX code from a standalone file into a function in my controller and can't seem to get it to display the JSON data in the autocomplete function in the view. I've verified that the function does return JSON encoded data by visiting the function URL directly.
Here's my JavaScript from the head of my view:
<script type="text/javascript">
$(document).ready(function(){
var ac_config = {
source: <?php echo base_url() . 'admin/lookup_tmdb_movie_titles'; ?>
select: function(event, ui){
$("#title").val(ui.item.title);
$("#year").val(ui.item.year);
$("#imdb_link").val(ui.item.imdb_link);
},
minLength:2,
position: {
my: "left top",
at: "left bottom",
collision: "none",
of: "#title.ui-autocomplete-input.ui-autocomplete-loading"
}
};
$("#title").autocomplete(ac_config);
});
</script>
Here's the function in the admin controller (I'm just using hard-coded test data until I get this working correctly):
function lookup_tmdb_movie_titles()
{
$term = 'test';
// TEST DATA
$title['title'] = 'test';
$title['label'] = 'test (2012)';
$title['value'] = 'test';
$title['year'] = '2012';
$title['imdb_link'] = 'testlink';
$matches[] = $title;
// convert into JSON format and output
$matches = array_slice($matches, 0, 5);
$this->output->set_output( json_encode($matches) );
}
I've also tried outputting the JSON the following two ways, all of which work if I go to the function directly via the URL, but none of which work in the view itself.
print json_encode($matches);
and
$data['json'] = json_encode($matches);
$this->load->view('admin/json_view', $data);
I've looked at a lot of posts on StackOverflow and via Google (hence the different output methods above) but nothing has seemed to solve the issue yet.
first you should try this:
source: "<?php echo site_url(admin/lookup_tmdb_movie_titles); ?>"
then this could be:
function lookup_tmdb_movie_titles()
{
$term = 'test';
// TEST DATA
$title['title'] = 'test';
$title['label'] = 'test (2012)';
$title['value'] = 'test';
$title['year'] = '2012';
$title['imdb_link'] = 'testlink';
$matches[] = $title;
// convert into JSON format and output
$matches = array_slice($matches, 0, 5);
var_dump($matches); //comment this if everythings ok
// echo json_encode($matches); ->uncomment this if everythings ok
}
then open firebug launch the ajax request and check the response in console.
AJAX code:
<script type="text/javascript">
function doCalc(){
var roomX = $('#room_str').val();
var heightX = $('#height_str').val();
var widthX = $('#width_str').val();
var prodid = $('#prodid').val();
var qtyX = $('#qty_str').val();
$.post('db_query.php',
{qtyX:qtyX, roomX:roomX, heightX:heightX, widthX:widthX, prodid:prodid},
function(data) {
data = $.parseJSON(data);
$('#width-placeholder').html(data.width);
$('#height-placeholder').html(data.height);
// ...
});
return false;
};
</script>
PHP Code:
<?php
include('db_pbconnection.php');
$query = mysql_query(" SELECT * FROM price_dimensions WHERE prodid = '".$_POST['prodid']."' AND height >= '".$_POST['heightX']."' AND width >= '".$_POST['widthX']."' ORDER BY height ASC, width ASC LIMIT 1 ");
$results = array();
$row = mysql_fetch_array($query);
$results = array(
'width' => $row['width'],
'height' => $row['height'],
'price' => $row['price']
);
$json = json_encode($results);
echo $json;
?>
EDIT: Updated code works successfully thanks to Alex. This uses json_encode to send the data back with ability to assign each SQL row to an identified for placeholders. This is just in case you need to move your data around individually in a layout.
If I'm not mistaken, what you try to do is apply selectors to HTML data coming from AJAX request. Yes? I don't think jQuery would help you here.
An option might be to have this div structure already on page as some template with placeholders. And your AJAX calls should return data in JavaScript native, parsable format - JSON. PHP has a function which will make JSON for you - json_encode. After you get JSON from your server, you can do this:
function(data) {
data = $.parseJSON(data);
$('#width-placeholder').html(data.width);
$('#height-placeholder').html(data.height);
// ...
});
return false;
};