i got this code that keep on returning undefined msg instead of the expected html.
Purpose of function:
the purpose of the below function is to return notifications in away similar to fb one's. the code is working fine. but there's something wrong with the getJSON part that i couldn't figure out. so instead of returning "clonex1 likes your post" i get undefined.
the code
function buzzme()
{
jQuery('#cnumber').removeClass();
jQuery('#cnumber').empty();
jQuery('#floating_box').toggle();
var nHeader = '<div id="floating_box" class="fb">' +
'<div id="header"><span id="htext">Notifications</span></div>' +
'<div id="int">' +
'<div id="bodyx">' +
'<ul>';
var nFooter = '</ul>' +
'<div class="jfooter">' +
'See all notifications' +
'</div>' +
'</div>' +
'</div>' +
'</div>';
var nContent;
jQuery.getJSON('notifications.php', {'n':1,'dht':3692}, function(response){
jQuery.each(response, function(i, nt2){
nContent += '<li id="lix">sdfsdfsd'+nt2.img+' '+nt2.notifier+'</li>';
})
});
alert(nContent);
var nFinal = nHeader+nContent+nFooter;
if (!jQuery('#floating_box').length) {
jQuery('body').append(nFinal);
}
}
notifications.php - setUpFlayout(); and setUpJSONList()
function setUpFlyout() {
$notify = new se_notify();
$data2 = $notify->notify_summary();
$trk = 0;
if($data2['total'] >= 1) {
for($i = 0; $ $i <= $data2['total']; $i++) {
$nid = $data2['notifys'][$i]['notify_id'];
$im = $data2['notifys'][$i]['notify_icon'];
$img = "<img src='./images/icons/$im' />";
$notifier = $data2['notifys'][$i]['notify_text'][0];
$atype = $data2['notifys'][$i]['notifytype_id'];
$url = '';
$url2 = $data2['notifys'][$i]['notify_url'];
if($atype == 1) {
$url = ' has sent you friend <a href='.$url2.'>request</a>';
}
$trk++;
if($data2['total'] >= 2) {
$ret_arr = '';
if($i == 0) {
$ret_arr = '[';
}
$ret_arr = $ret_arr.setUpJSONList($data2['total'], $nid, $img, $notifier, $url, $trk);
if($i == $data2['total']-1) {
$ret_arr = $ret_arr.']';
}
echo '';
} else if($data2['total'] == 1){
//$ret_arr = '[{"dh3":"'.$data2['total'].'","nid":"'.$nid.'", "img":"'.$img.'","notifier":"'.$notifier.'","url":"'.$url.'"}]';
$ret_arr = '';
echo $ret_arr;
}
if($i == ($data2['total']-1))
break;
}
}
}
setUpJSONList();
function setUpJSONList($total, $nid, $img, $notifier, $url, $track) {
$comma = ',';
$lp = '';
$rp = ']';
$result = '';
if($track == $total) {
$result = '{"pos":"'.$track.'","dh3":"'.$total.'","nid":"'.$nid.'","img":"'.$img.'","notifier":"'.$notifier.'", "url":"'.$url.'"}';
} else {
$result = '{"pos":"'.$track.'","dh3":"'.$total.'","nid":"'.$nid.'","img":"'.$img.'","notifier":"'.$notifier.'", "url":"'.$url.'"},';
}
return $result;
}
thanks
Your usage of nContent after getJSON might be undefined since getJSON is asynchronous and would not have completed initializing nContent. You need to move the code using nContent inside the callback of getJSON.
jQuery.getJSON('notifications.php', {'n':1,'dht':3692}, function(response){
jQuery.each(response, function(i, nt2){
nContent += '<li id="lix">sdfsdfsd'+nt2.img+' '+nt2.notifier+'</li>';
})
alert(nContent);
var nFinal = nHeader+nContent+nFooter;
if (!jQuery('#floating_box').length) {
jQuery('body').append(nFinal);
}
});
Related
I experience an issue with getting values from an array. For some reason I can't get it to work (just getting [object]) and appreciate any help here:
Here I'm creating the response
foreach ($locations as $location) {
if($location->getStreet1() != ''){
$result .= $location->getStreet1() .', ';
}
if($location->getCity() != ''){
$result .= $location->getCity() .', ';
}
$locationList[$i]['location'] = addslashes(htmlspecialchars($location->getName()));
$locationList[$i]['address'] = addslashes(htmlspecialchars($result));
$i++;
$result = '';
}
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode(array('locations' => $locationList)));
And here I'm handling the response:
request.done(function(data) {
var container = jQuery('#hotel-list-container');
var locations = jQuery.parseJSON(data).locations;
container.html('');
var firstSymbols = [];
locations.forEach(function(location) {
var firstSymbol = location.location;
if (jQuery.inArray(firstSymbol, firstSymbols) === -1) {
firstSymbols.push(firstSymbol);
}
});
firstSymbols.forEach(function(firstSymbol) {
if (jQuery.isNumeric(firstSymbol)) {
if (container.find('.numeric').size() === 0) {
container.append('<div class="numeric">0–9</div>');
}
} else {
container.append('<div class="letter">' + firstSymbol + '</div>');
}
locations.forEach(function(data) {
if (firstSymbol == data.location) {
container.append('<div class="hotel-item"><a class="hotel" data-id="' + data.location + '"><div class="hotel_addr_div"><span>' + data.location +'</span>'+data.address+'</div></a></div>');
console.log(data.location);
}
});
});
container.slideDown(null, function() {
jQuery('#hotel-list-container').mCustomScrollbar({ scrollInertia: 0 });
});
});
locations.forEach(function(data) {
if (firstSymbol == data.location) {
container.append('<div class="hotel-item">
<a class="hotel" data-id="' + data.location + '">
<div class="hotel_div"><span>' + data.location +'</span>'+data.address+'</div>
</a>
</div>');
}
And that is what I'm seeing in frontend
<div class="hotel-lists" id="hotel-list-container-mobile" style="max-height: 497px;">
<div class="letter">undefined</div>
<div class="hotel-item"><a class="hotel" data-id="[object Object]">[object Object]</a></div>
<div class="hotel-item"><a class="hotel" data-id="[object Object]">[object Object]</a></div>
<div class="hotel-item"><a class="hotel" data-id="[object Object]">[object Object]</a></div>
</div>
Thanks for all answers. Like requested I added the full code in here
guys i keep on getting this uncaught syntaxerror:unexpected token <, and it points to the jquery library file,i am making a request to AJAX(comment-insert-ajax.php) using JQuery(comment-insert.js),i try removing the closing token of php(?>) in the AJAX script but i still get the error.I actually get the error when i add the 'require_once' lines,sorry about that.
comment-insert-ajax.php
<?php
if(isset($_POST['task']) && $_POST['task'] == 'comment-insert')
{
$userId = (int)$_POST['userId'];
$comment = addslashes(str_replace("\n","<br>",$_POST['comment']));
$std = new stdClass();
$std->comment_id = 24;
$std->userId = $userId;
$std->comment = $comment;
$std->userName = "Thabo Ambrose";
$std->profile_img= "images/tbo.jpg";
require_once $_SERVER['DOCUMENT_ROOT'] . 'defines.php';
require_once MODELS_DIR . 'Comments.php';
echo json_encode($std);
}
else
{
header('location: /');
}
and following is the Jquery file that makes the request using the '$.post' method.
comment-insert.js
$(document).ready(function(){
$('#comment-post-btn').click(function(){
comment_post_btn_click();
});
});
function comment_post_btn_click()
{
var _comment = $('#comment-post-text').val();
var _userId = $('#user-id').val();
var _userName = $('#user-name').val();
if(_comment.length > 0 && _userId != null)
{
//proceed with ajax call back
$.post("ajax/comment-insert-ajax.php",
{
task : "comment-insert",
userId : _userId,
comment : _comment
}
).error(
function()
{
console.log("Error : ");
}
).success(
function(data)
{
comment_insert(jQuery.parseJSON(data));
console.log("Response text : "+ data);
}
);
console.log(_comment + " "+_userName + " id of "+_userId);
}
else
{
//do something
$('#comment-post-text').addClass('alert alert-danger');
$('#comment-post-text').focus(function(){$('#comment-post-text').removeClass('alert alert-danger');});
}
//remove text in the text area after posting
$('#comment-post-text').val("");
}
function comment_insert(data)
{
var t = '';
t += '<li class="comment-holder" id="_'+data.comment_id+'">';
t += '<div class="user-img">';
t += '<img src="'+data.profile_img+'" class="user-img-pic">';
t += '</div>';
t += '<div class="comment-body">';
t += '<h3 class="username-field">'+data.userName+'</h3>';
t += '<div class="comment-text">'+data.comment+'</div>';
t += '</div>';
t += '<div class="comment-buttons-holder">';
t += '<ul>';
t += '<li class="delete-btn">x</li>';
t += '</ul>';
t += '</div>';
t += '</li>';
$('.comments-holder-ul').prepend(t);
}
The error points to line 7497 of the jQuery library,it point to the following code
jQuery.parseJSON = function(data)
{
return data;
}
Try using the JSON.parse function:
//proceed with ajax call back
$.post("ajax/comment-insert-ajax.php",
{
task : "comment-insert",
userId : _userId,
comment : _comment
}
).error(
function()
{
console.log("Error : ");
}
).success(
function(data)
{
comment_insert(JSON.parse(data));
console.log("Response text : "+ data);
}
);
console.log(_comment + " "+_userName + " id of "+_userId);
}
try puting the data in a array and then encode it
$array = ['comment_id' => 24,'userId' => $userId,'comment' => $comment,'userName' => "Thabo Ambrose",'profile_img'= "images/tbo.jpg"];
echo json_encode($array);
change if(isset($_POST['task']) && $_POST['task'] == 'comment-insert') this line of code to if(isset($_POST['task']) && isset($_POST['task'])&&$_POST['task']== 'comment-insert').
then change the ajax call to
$.ajax({
url: "ajax/comment-insert-ajax.php",
data :{"task":"comment-insert","UserId":_userId,"comment":_comment},
type: "POST",
dataType: "json",
success:function(msg) {
}
});
I'm trying to build a simple news page with ajax filters depending on what category the user wants to see. The javascript below connects to a php file and outputs HTML with data from the mysql database. I need to know how to tell the JS to put the data from the "heading" column into a php variable so that it wraps it in the correct href link.
This is the php that creates the heading and the link
$data_fields = '`id`, `heading`, `date`, `copy`, `summary`, `article`, `press_release`, `video`';
$from = '`media`';
$news_result = $db->selectByStrings($data_fields, $from, $where_conditions, $order_by);
$news = $db->getAllRows($news_result);
foreach ($news as $new) {
echo '<h2 class="news"><a class="news" href="'.$base_href.$new['id'].'">'.$new['heading'].'</a></h2>';
}
I somehow need to include this is the separate JS file, making sure it is only applied to data from the heading column.
Javascript
function makeTable(data) {
var tbl_body = "";
$.each(data, function () {
var tbl_row = "";
$.each(this, function (k, v) {
tbl_row += "<div class='row'><div class='col-md-8 col-md-offset-2'>" + v + " </div></div>";
});
tbl_body += "<div class='non-white'>" + tbl_row + "</div>";
});
return tbl_body;
}
function getEmployeeFilterOptions() {
var opts = [];
$checkboxes.each(function () {
if (this.checked) {
opts.push(this.name);
}
});
return opts;
}
function updateEmployees(opts) {
$.ajax({
type: "POST",
url: "filter3.php",
dataType: 'json',
cache: false,
data: {filterOpts: opts},
success: function (records) {
$('#employees div').html(makeTable(records));
}
});
}
var $checkboxes = $("input:checkbox");
$checkboxes.on("change", function () {
var opts = getEmployeeFilterOptions();
updateEmployees(opts);
});
updateEmployees();
The php file the above connects to:
<?php
$pdo = new PDO('mysql:host=localhost;dbname=xxx', 'xxx', 'xxx');
$select = 'SELECT heading, summary, created_date';
$from = ' FROM media';
$where = ' WHERE TRUE';
$opts = isset($_POST['filterOpts']) ? $_POST['filterOpts'] : array('');
if (in_array("article", $opts)) {
$where .= " AND article = 1";
}
if (in_array("press_release", $opts)) {
$where .= " AND press_release = 1";
}
if (in_array("video", $opts)) {
$where .= " AND video = 1";
}
$sql = $select.$from.$where;
$statement = $pdo->prepare($sql);
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo($json);
?>
I think you are looking for something like this :
var base_href = 'http://www.stackoverflow.com/';
function makeTable(data) {
var tbl_body = "";
$.each(data, function (index, row) {
var tbl_row = "";
$.each(row, function (k, v) {
if(k == 'heading' && 'id' in row) {
v = '<a class="news" href="' + base_href + row.id +'">' + v + '</a>';
}
tbl_row += "<div class='row'><div class='col-md-8 col-md-offset-2'>"
+ v + " </div></div>";
});
tbl_body += "<div class='non-white'>" + tbl_row + "</div>";
});
return tbl_body;
}
I retrieved my list of users from my db and now I want to add them to my page. I am trying to display the users using a table and make sure that they appear four per row and then jump to the new row, but I am not certain how to do this. Here is my js file so far. Please let me know if there is anything else you need.
var space = new Array("username", "user_id","address","state","postal_code","phone","email");
$(document).ready( function() {
var obj = '';
$.getJSON( "obtainUsers.php", function(data) {
var num = 1;
var json = JSON.stringify(data);
obj = jQuery.parseJSON(json);
var html = "";
var tot_obj = obj.length ;
var upper = (num*10)-1;
var lower = (num*10)-10;
var max = ( upper < tot_obj ) ? upper : tot_obj ;
html += "<div><table width:'100%'><tr>";
for (var i = lower; i <= max-1 ; i++ )
{
var toggle = i % 2;
var list_items = "";
columns.forEach( function(col)
{
if ( obj[i][col] != null ) {
if ( obj[i][col] !== "" )
{
if ( obj[i].level == 'NEW' ) {
list_items += "<div class='new_client'>";
list_items += obj[i][col] + "</div >";
}
else if( obj[i].level == 'RENEWAL' ) {
list_items += "<div class='renewing_client'>";
list_items += obj[i][col] + "</div >";
}
else if( obj[i].level == 'CURRENT' ) {
list_items += "<div class='current_client';>";
list_items += obj[i][col] + "</div >";
//console.log(obj[i][col]);
}
}
}
} );
list_items += "</br >";
if ( toggle == 0 )
{
html += "<td><div class='table_styles'> ";
html += list_items ;
//console.log(list_items);
html += "</div></td>";
console.log(html);
}
else
{
html += "<td><div class='table_styles'> ";
html += list_items;
html += "</div></td>";
}
}
html += "</tr> </table></div>";
$('.runninglist').html(html);
});
});
var columns = ["username","user_id","address","state","postal_code","phone","email"];
var level_classes = {"NEW":"new_client", "RENEWAL":"renewing_client", "CURRENT":"current_client"};
$(document).ready( function() {
$.getJSON("obtainUsers.php", function(data) {
var $table = $('<table style="width: 100%;">');
var $tbody = $('<tbody>');
$table.append($tbody);
var $tr = null;
data.forEach(function(user, index){
if(index % 4 === 0) {
$tr = $('<tr>');
$tbody.append($tr);
}
$td = $('<td class="'+level_classes[user.level]+'">');
columns.forEach(function(col){
$td.append(user[col]);
$td.append($('<br>'));
});
$tr.append($td);
});
$('.runninglist').append($table);
});
});
I have the magneto extension "Codnitive Sidenav" but in order to make it slideUp/Down
some extra coding is needed.
the original navigation.phtml code for sidenav is:
<?php if ($categories = $this->getCategoriesNavMenu()): ?>
<div id="sidebar-nav" class="block sidebar-nav-left <?php echo $this- >getBlockAlias() ?>">
<div class="block-title">
<strong><span><?php echo $this->__($this->getTitle()) ?></span></strong>
</div>
<div class="block-content">
<ul id="sidebar-nav-menu">
<?php if ($this->showHome()): ?>
<li class="<?php echo $this->getHomeClasses() ?>">
<a title="Go to Home Page" href="<?php echo $this->getBaseUrl() ?>"><span class="category_name"></span></a>
</li>
<?php endif; ?>
<?php echo $categories; ?>
</ul>
<?php if ($this->showSupportLogo()): ?>
<div class="clearer support-logo-wrapper"></div>
<a href="http://www.codnitive.com/" target="_blank" class="support_logo">
<?php if ($this->showAsImage()): ?>
<img src="<?php echo $this->getSkinUrl('images/codnitive/sidenav/codnitive_logo.png'); ?>" alt="CODNITIVE®" title="Sidebar Navigation by CODNITIVE"/>
<?php else: ?>
<span>CODNITIVE®</span>
<?php endif; ?>
</a>
<?php endif; ?>
</div>
<?php if ($this->getConfig()->isCollapsible()): ?>
<script type="text/javascript" language="javascript">
//<![CDATA[
Codnitive = {
expandMenu: function(parent)
{
var mode = parent.getElementsByTagName("ul")[0].getAttribute("expanded");
(mode == 1) ? Codnitive.collapse(parent) : Codnitive.expand(parent);
},
expand: function(parent)
{
parent.getElementsByTagName("ul")[0].style.display = "block";
parent.getElementsByTagName("span")[0].style.backgroundPosition = "right center";
parent.getElementsByTagName("ul")[0].setAttribute("expanded", "1");
},
collapse: function(parent)
{
parent.getElementsByTagName("ul")[0].style.display = "none";
parent.getElementsByTagName("span")[0].style.backgroundPosition = "left center";
parent.getElementsByTagName("ul")[0].setAttribute("expanded", "0");
}
};
//]]>
</script>
<?php endif; ?>
and the original code for navigation.php is:
<?php
*/
public function getConfig()
{
if ($this->_config === null) {
$this->_config = Mage::getModel('sidenav/config');
}
return $this->_config;
}
/**
* Get store categories navigation menu
*
* #return string
*/
public function getCategoriesNavMenu()
{
$navigationMenu = $this->renderCategoriesMenuHtml(0);
return $navigationMenu ? $navigationMenu : false;
}
/**
* We set cache to null when product direct access option is enabled and customer
* is in product page to avoid wrong category tree showing with enabled caches
*
* Adds 1 extra second to page load
* Ultra version has caching and best performance
*
* #return null
*/
public function getCacheLifetime()
{
$condition = (Mage::registry('current_product') !== null)
&& ($this->getConfig()->activeProductCategoriesInDirectAccess());
if ($condition) {
return null;
}
return parent::getCacheLifetime();
}
/**
* Get catagories of current store
*
* #return Varien_Data_Tree_Node_Collection
*/
public function getStoreCategories()
{
return Mage::helper('sidenav/category')->getStoreCategories();
}
/**
* Returns category model
*
* #return Codnitive_Sidenav_Model_Category
*/
protected function _getCategoryModel()
{
return Mage::getModel('sidenav/catalog_category');
}
/**
* Retruns data helper
*
* #return Codnitive_Sidenav_Helper_Data
*/
protected function _getHelper()
{
return Mage::helper('sidenav');
}
/**
* Render category to html
*
* #param Mage_Catalog_Model_Category $category
* #param int Nesting level number
* #param boolean Whether ot not this item is last, affects list item class
* #param boolean Whether ot not this item is first, affects list item class
* #param boolean Whether ot not this item is outermost, affects list item class
* #param string Extra class of outermost list items
* #param string If specified wraps children list in div with this class
* #param boolean Whether ot not to add on* attributes to list item
* #return string
*/
protected function _renderCategoryMenuItemHtml(
$category, $level = 0, $isLast = false,
$isFirst = false, $isOutermost = false, $outermostItemClass = '',
$childrenWrapClass = '', $noEventAttributes = false
) {
if (!$category->getIsActive()) {
return '';
}
$config = $this->getConfig();
$html = array();
$expanded = null;
$ulThumb = '';
$image = '';
$thumb = '';
$htmlLi = '';
// get all children
if (Mage::helper('catalog/category_flat')->isEnabled()) {
$children = (array) $category->getChildrenNodes();
$childrenCount = count($children);
}
else {
$children = $category->getChildren();
if (!$this->_getHelper()->isSearchResultsPage()) {
$childrenCount = $children->count();
}
else {
if (is_string($children)) {
$children = explode(',', $children);
}
$childrenCount = count($children);
}
}
// select active children
$activeChildren = array();
foreach ($children as $child) {
if ($child->getIsActive()) {
$activeChildren[] = $child;
}
}
$activeChildrenCount = count($activeChildren);
$hasActiveChildren = ($activeChildrenCount > 0);
// prepare list item html classes
$classes = array();
$classes[] = 'level' . $level;
$classes[] = 'nav-' . $this->_getItemPosition($level);
if ($this->isCategoryActive($category)) {
$classes[] = 'active';
}
else if ((Mage::registry('current_product') !== null) && ($config->activeProductCategoriesInDirectAccess())) {
$classes = $this->_getCategoryModel()->getProductCategoriesInDirectAccess($category, $classes);
}
$linkClass = '';
if ($isOutermost && $outermostItemClass) {
$classes[] = $outermostItemClass;
$linkClass = ' class="' . $outermostItemClass . '"';
}
if ($isFirst) {
$classes[] = 'first';
}
if ($isLast) {
$classes[] = 'last';
}
if ($hasActiveChildren) {
$classes[] = 'parent';
}
// prepare list item attributes
$attributes = array();
if (count($classes) > 0) {
$attributes['class'] = implode(' ', $classes);
}
if ($hasActiveChildren && !$noEventAttributes) {
$attributes['onmouseover'] = 'toggleMenu(this,1)';
$attributes['onmouseout'] = 'toggleMenu(this,0)';
}
// assemble list item with attributes
$thumbWidth = 14;
$thumbHeight = 14;
$thumbPosition = $config->getThumbPosition();
$liMarginLeft = 0;
$ulMarginLeft = 5;
$ulPaddingLeft = 10;
// define image thumbnail variables
if ($config->isThumbImageActive()) {
if ($config->getThumbSize()) {
$thumbWidth = $config->getThumbWidth();
$thumbHeight = $config->getThumbHeight();
}
$thumbnail = $this->_getCategoryModel()->load($category->getId())->getThumbnailImageUrl();
$ulThumb = ' ul-thumb';
if (!empty($thumbnail)) {
$image = '<img class="thumb-img-' . $thumbPosition . '" src="' . $thumbnail . '" style= "width:' . $thumbWidth . 'px; height:' . $thumbHeight . 'px; float: ' . $thumbPosition . ';" />';
$thumb = ' thumb';
if ($thumbPosition === 'left') {
if ($config->isCollapsible() && $config->isThumbImageActive()) {
$liMarginLeft = $thumbWidth + 3;
$ulMarginLeft = 0;
}
else {
$liMarginLeft = 0;
$ulMarginLeft = $thumbWidth + 3;
}
$ulPaddingLeft = 0;
}
}
else {
$thumb = ' no-thumb';
$liMarginLeft = ($thumbPosition === 'right') ? 0 : $thumbWidth + 3;
if ($thumbPosition === 'left') {
$ulMarginLeft = 0;
$ulPaddingLeft = 0;
}
}
}
$collapsibleClass = '';
if ($config->isCollapsible()) {
$collapsibleClass = ' collapsible';
}
// add collapsible arrow and wrraper
$arrow = '';
$extraStyle = '';
$collapsibleIconPosition = $config->getCollapsibleIconPosition();
if ($config->isCollapsible()) {
$width = $config->getCollapsibleIconType() === 'arrow' ? 8 : 16;
$height = 0;
$expanded = 0;
if ($hasActiveChildren) {
$width = $config->getCollapsibleIconType() === 'arrow' ? 8 : 16;
$height = 16;
}
if ($height == 0) {
$extraStyle = ' display:none;';
}
if ($height == 0 && $collapsibleIconPosition === 'left') {
$liMarginLeft += $width;
}
if ($this->isCategoryActive($category)) {
$expanded = 1;
}
$expanded = ' expanded="' . $expanded .'"';
$spanOnclick = 'onclick="Codnitive.expandMenu(this.parentNode)';
$spanClass = $config->getCollapsibleIconType() . '-' . $collapsibleIconPosition;
$arrow = '<span class="' . $spanClass . ' " ' . $spanOnclick . '" style="width: ' . $width . 'px; height: ' . $height . 'px;' . $extraStyle . '"></span>';
}
$htmlLi .= '<li';
foreach ($attributes as $attrName => $attrValue) {
$htmlLi .= ' ' . $attrName . '="' . str_replace('"', '\"', $attrValue) . $thumb . $collapsibleClass . '"';
}
$htmlLi .= ' style="margin-left: ' . $liMarginLeft . 'px;' . '">';
$html[] = $htmlLi;
$html[] = $arrow;
// add wrapper
$aClass = '';
$aStyle = '';
$onclick = '';
if ($config->isCollapsible() || $config->isThumbImageActive()) {
$wrapperMargin = ($config->isCollapsible() && $collapsibleIconPosition === 'left') ? 14 : 0;
$extraMargin = !$config->isThumbImageActive() ? 0 : (!empty($thumbnail) && ($thumbPosition === 'left')) ? $thumbWidth + 3 : 0;
$collWrapper = $wrapperMargin + $extraMargin;
// makes parent category name clickable to open/close collapsible menus if option is enabled
$collapseName = '';
if ($hasActiveChildren && $config->isCollapsible() && $config->expandByParentName()) {
$onclick = ' onclick="Codnitive.expandMenu(this.parentNode);return false;"';
$collapseName = ' collapse-name';
}
$aClass = 'class="collapsible-wrapper' . $collapseName . '"';
$aStyle = ' style="margin-left: ' . $collWrapper . 'px;"';
}
$html[] = '<a ' . $aClass . $onclick . 'href="' . $this->getCategoryUrl($category) . '"'
. $linkClass .'>' . '<span class="category_name">'
. $this->escapeHtml($category->getName()) . '</span></a>';
// add thumbnail image
$html[] = $image;
// add product count
if ($config->showProductCount()) {
$count = Mage::getModel('catalog/layer')
->setCurrentCategory($category->getID())
->getProductCollection()
->getSize();
if (($config->removeZeroCount() && $count > 0) || !$config->removeZeroCount()) {
$html[] = '<span class="product-count">(' . $count . ')</span>';
}
}
// render children
$htmlChildren = '';
$j = 0;
foreach ($activeChildren as $child) {
$htmlChildren .= $this->_renderCategoryMenuItemHtml(
$child, ($level + 1), ($j == $activeChildrenCount - 1), ($j == 0), false, $outermostItemClass, $childrenWrapClass, $noEventAttributes
);
$j++;
}
if (!empty($htmlChildren)) {
if ($childrenWrapClass) {
$html[] = '<div class="' . $childrenWrapClass . '">';
}
$html[] = '<ul class="level' . $level . $ulThumb . $collapsibleClass .
'" style="margin-left: ' . $ulMarginLeft .
'px; padding-left: ' . $ulPaddingLeft . 'px;"' . $expanded . '>';
$html[] = $htmlChildren;
$html[] = '</ul>';
if ($childrenWrapClass) {
$html[] = '</div>';
}
}
$html[] = '</li>';
$html = implode("\n", $html);
return $html;
}
/**
* Render categories menu in HTML
*
* #param int Level number for list item class to start from
* #param string Extra class of outermost list items
* #param string If specified wraps children list in div with this class
* #return string
*/
public function renderCategoriesMenuHtml($level = 0, $outermostItemClass = '', $childrenWrapClass = '')
{
$currentId = Mage::app()->getStore()->getRootCategoryId();
$currentLevel = $this->_getCategoryModel()->load($currentId)->getLevel();
if ($registerdCategory = Mage::registry('current_category')) {
$currentId = $registerdCategory->getId();
$currentLevel = $registerdCategory->getLevel();
}
$config = $this->getConfig();
$paretnType = $config->getParent();
$categories = $this->getStoreCategories();
$activeCategories = array();
foreach ($categories as $child) {
// this condition use for "Current Category and Children" option
$condition = ($paretnType == 'current')
&& ($child->getLevel() == $currentLevel)
&& ($child->getId() != $currentId);
if ($child->getIsActive() && !$condition) {
$activeCategories[] = $child;
}
}
$activeCategoriesCount = count($activeCategories);
$hasActiveCategoriesCount = ($activeCategoriesCount > 0);
if (!$hasActiveCategoriesCount) {
return '';
}
$html = '';
$j = 0;
foreach ($activeCategories as $category) {
$html .= $this->_renderCategoryMenuItemHtml(
$category, $level, ($j == $activeCategoriesCount - 1),
($j == 0), true, $outermostItemClass, $childrenWrapClass, true
);
$j++;
}
return $html;
}
/**
* Get category title
*
* #return string
*/
public function getTitle()
{
$title = '';
$currentCategory = Mage::registry('current_category');
switch ($this->getConfig()->getTitleType()) {
case 'current':
if ($currentCategory) {
$title = $currentCategory->getName();
}
break;
case 'parent':
if ($currentCategory) {
$parent = $currentCategory->getParentCategory();
$rootId = Mage::app()->getStore()->getRootCategoryId();
if ($parent->getId() != $rootId) {
$title = $parent->getName();
}
}
break;
case 'static':
$title = $this->getConfig()->getStaticTitle();
}
if (!$title) {
$title = $this->getConfig()->getStaticTitle();
}
return $title;
}
/**
* Retrieves home page link must show
*
* #return boolean
*/
public function showHome()
{
if ($this->_getHelper()->isHome() && $this->getConfig()->removeHomeInHome()) {
return false;
}
return $this->getConfig()->showHome();
}
/**
* Returns all classes for home link
*
* #return string
*/
public function getHomeClasses()
{
$classes = 'level0 nav-0 parent home';
if ($this->getConfig()->isCollapsible()) {
$classes .= ' collapsible';
}
if ($this->_getHelper()->isHome()) {
$classes .= ' active';
}
return $classes;
}
/**
* Retrieves which CODNITIVE logo must show or not
*
* #return boolean
*/
public function showSupportLogo()
{
return $this->getConfig()->showSupportLogo();
}
/**
* Retrieves which CODNITIVE logo must show as image or text
*
* #return boolean
*/
public function showAsImage()
{
return $this->getConfig()->showAsImage();
}
/**
* Get extension enable status
*
* #deprecated after 1.7.20
* We don't need to check for module activation option
* in template, we check it in layout.
*
* #return boolean
*/
public function isActive()
{
return $this->getConfig()->isActive();
}
/**
* Get selected column
*
* #deprecated after 1.7.20
* We don't need to check for selected column option
* in template, we check it in layout.
*
* #return string
*/
public function getColumn()
{
return $this->getConfig()->getColumn();
}
}
I was told to replace the javascript code in navigation.phtml with the code here below:
(function($) {
Codnitive = {
sideMenu:
{
expandMenu: function($parent)
{
var $ul = $parent.getElementsByTagName("ul")[0];
var $span = $parent.getElementsByTagName("span")[0];
($ul.getAttribute("expanded") == 1)
? Codnitive.sideMenu.collapse($ul, $span)
: Codnitive.sideMenu.expand($ul, $span);
},
expand: function($ul, $span)
{
$($ul).slideDown(300, function() {
$ul.setAttribute("expanded", "1");
$span.style.backgroundPosition = "right center";
});
},
collapse: function($ul, $span)
{
$($ul).slideUp(400, function() {
$ul.setAttribute("expanded", "0");
$span.style.backgroundPosition = "left center";
});
}
},
})(jQuery);
AND call it like this:
onclick="Codnitive.sideMenu.expandMenu(this.parentNode)"
so I tried this, like so:
$expanded = ' expanded="' . $expanded .'"';
$spanOnclick = 'onclick="Codnitive.expandMenu(this.parentNode)';
$spanClass = $config->getCollapsibleIconType() . '-' . $collapsibleIconPosition;
$arrow = '<span class="' . $spanClass . ' " ' . $spanOnclick . '" style="width: ' . $width . 'px; height: ' . $height . 'px;' . $extraStyle . '"></span>';
and
if ($hasActiveChildren && $config->isCollapsible() && $config->expandByParentName()) {
$onclick = ' onclick="Codnitive.sideMenu.expandMenu(this.parentNode);return false;"';
But it didn't work so my question is: What am I doing wrong here?
does it have to do with the misplacement of " "?
Does anyone know what I should do to make this work?
much obliged,
Tuutuutuut