Rendering DataTable from MySQL Database with php through JSON - javascript

I am trying to render a DataTable on a webpage through JSON with php getting the data from a MySQL Database. But I am not getting it anyhow.. I get the JSON-File printed out (echo), but the DataTable is not rendered, and when opening the page I get an error: "....DataTable #xxxxx - Invalid JSON response..." But the JSON is right, I tested it with many JSON Validators. I Think it's just not formatted the way a DataTable should accept it.
Here is my JSON format, that get's printed out (echo), to test what I am becoming from the server:
{
"aaData":[
[
"id12345",
"bchange122",
"textHEre",
"https://url.here.com/images/ppp.png!",
"hellooooo",
"https://kbkbkbk.hello.com/subid=[usr.nr]-[b_tt]|[ba_ba]|[category]"
],
[
"id23456",
"test122",
"test2HEre",
"https://url.here.com/images/ppp.png!",
"huhuhu",
"https://kbkbkbk.hello.com/subid=[usr.nr]-[b_tt]|[ba_ba]|[category]"
],
[
"id34567",
"test233",
"test344HEre",
"https://url.here.com/images/ppp.png!",
"ohlll",
"https://kbkbkbk.hello.com/subid=[usr.nr]-[b_tt]|[ba_ba]|[category]"
],
[
"id45678",
"test344",
"test4555Here",
"https://url.here.com/images/ppp.png!",
"eholl",
"https://kbkbkbk.hello.com/subid=[usr.nr]-[b_tt]|[ba_ba]|[category]"
]
]
}
It is generated from this php:
<?php
/* Array of database columns which should be read and sent back to DataTables. Use a space where
* you want to insert a non-database field (for example a counter or static image)
*/
$aColumns = array( 'pId', 'sName', 'lName', 'pLogUrl', 'incent', 'det_sUrl');
/* Indexed column (used for fast and accurate table cardinality) */
$sIndexColumn = "id";
/* DB table to use */
$sTable = "tableName_here";
/* Database connection information */
$gaSql['user'] = "userHere";
$gaSql['password'] = "passHere";
$gaSql['db'] = "dataBaseHEre";
$gaSql['server'] = "serverHere";
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* If you just want to use the basic configuration for DataTables with PHP server-side, there is
* no need to edit below this line
*/
/*
* MySQL connection
*/
$gaSql['link'] = mysql_pconnect( $gaSql['server'], $gaSql['user'], $gaSql['password'] ) or
die( 'Could not open connection to server' );
mysql_select_db( $gaSql['db'], $gaSql['link'] ) or
die( 'Could not select database '. $gaSql['db'] );
/*
* Paging
*/
$sLimit = "";
if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' )
{
$sLimit = "LIMIT ".mysql_real_escape_string( $_GET['iDisplayStart'] ).", ".
mysql_real_escape_string( $_GET['iDisplayLength'] );
}
/*
* Ordering
*/
if ( isset( $_GET['iSortCol_0'] ) )
{
$sOrder = "ORDER BY ";
for ( $i=0 ; $i<intval( $_GET['iSortingCols'] ) ; $i++ )
{
if ( $_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" )
{
$sOrder .= $aColumns[ intval( $_GET['iSortCol_'.$i] ) ]."
".mysql_real_escape_string( $_GET['sSortDir_'.$i] ) .", ";
}
}
$sOrder = substr_replace( $sOrder, "", -2 );
if ( $sOrder == "ORDER BY" )
{
$sOrder = "";
}
}
/*
* Filtering
* NOTE this does not match the built-in DataTables filtering which does it
* word by word on any field. It's possible to do here, but concerned about efficiency
* on very large tables, and MySQL's regex functionality is very limited
*/
$sWhere = "";
if ( $_GET['sSearch'] != "" )
{
$sWhere = "WHERE (";
for ( $i=0 ; $i<count($aColumns) ; $i++ )
{
$sWhere .= $aColumns[$i]." LIKE '%".mysql_real_escape_string( $_GET['sSearch'] )."%' OR ";
}
$sWhere = substr_replace( $sWhere, "", -3 );
$sWhere .= ')';
}
/* Individual column filtering */
for ( $i=0 ; $i<count($aColumns) ; $i++ )
{
if ( $_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != '' )
{
if ( $sWhere == "" )
{
$sWhere = "WHERE ";
}
else
{
$sWhere .= " AND ";
}
$sWhere .= $aColumns[$i]." LIKE '%".mysql_real_escape_string($_GET['sSearch_'.$i])."%' ";
}
}
/*
* SQL queries
* Get data to display
*/
$sQuery = "
SELECT SQL_CALC_FOUND_ROWS ".str_replace(" , ", " ", implode(", ", $aColumns))."
FROM $sTable
$sWhere
$sOrder
$sLimit
";
$rResult = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
/* Data set length after filtering */
$sQuery = "
SELECT FOUND_ROWS()
";
$rResultFilterTotal = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
$aResultFilterTotal = mysql_fetch_array($rResultFilterTotal);
$iFilteredTotal = $aResultFilterTotal[0];
/* Total data set length */
$sQuery = "
SELECT COUNT(".$sIndexColumn.")
FROM $sTable
";
$rResultTotal = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
$aResultTotal = mysql_fetch_array($rResultTotal);
$iTotal = $aResultTotal[0];
/*
* Output
*/
$output = array(
"aaData" => array()
);
while ( $aRow = mysql_fetch_array( $rResult ) )
{
$row = array();
for ( $i=0 ; $i<count($aColumns) ; $i++ )
{
if ( $aColumns[$i] == "version" )
{
/* Special output formatting for 'version' column */
$row[] = ($aRow[ $aColumns[$i] ]=="0") ? '-' : $aRow[ $aColumns[$i] ];
}
else if ( $aColumns[$i] != ' ' )
{
/* General output */
$row[] = $aRow[ $aColumns[$i] ];
}
}
$output['aaData'][] = $row;
}
$output = str_replace("\\/", "/", $output);
echo json_encode($output, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
?>
Here the Javascript-Code to render the DataTable from the JSON:
$(document).ready(function() {
$('#oShopPTable').DataTable( {
"bProcessing": true,
"bServerSide": true,
"ajax": "AdminPage.php",
"columns": [
{ "data": "pId" },
{ "data": "sName" },
{ "data": "lName" },
{ "data": "pLogUrl",
render : function( data, type, full, meta ) {
return type == 'display' ? '<img src="'+ data + '"/>' : data
}
},
{ "data": "incent" },
{ "data": "detsUrl",
render : function(data, type, full, meta) {
return type == 'display' ? 'Go Shop' : data
}
}
]
} );
} );
And here the HTML:
<div class="panel-body">
<table id="oShopPTable" class="display">
<thead>
<tr>
<th>P ID</th>
<th>S Name</th>
<th>L Name</th>
<th>P Log URL</th>
<th>Incentiv</th>
<th>Det S URL</th>
</tr>
</thead>
<tfoot>
<tr>
<th>P ID</th>
<th>S Name</th>
<th>L Name</th>
<th>P Log URL</th>
<th>Incentiv</th>
<th>Det S URL</th>
</tr>
</tfoot>
</table>
</div>
Since the echo of the output is coming on the page, the data get fetched from the database, and transformed to json, but not getting rendered as DataTable :-/ The form of the json is valid, but as I said, I think it's not the from the DataTable needs it. How can I turn it to that form in my code?
This javascript-code, which renders a DataTable from a JSON-file on the server (not getting the data from MySql-Server), works fine. It is another DataTable rendered on the same page:
$(document).ready(function() {
$('#oShopMobTable').DataTable( {
"ajax": "test.json",
"columns": [
{ "data": "pId" },
{ "data": "sName" },
{ "data": "lName" },
{ "data": "pLogUrl",
render : function( data, type, full, meta ) {
return type == 'display' ? '<img src="'+ data + '"/>' : data
}
},
{ "data": "incentiv" },
{ "data": "details.jToUrl",
render : function(data, type, full, meta) {
return type == 'display' ? 'Go Shop' : data
}
}
]
} );
} );
And the working table, is getting the data from the following test.json with this format:
{
"data": [
{
"sName": "hew",
"lName": "hewii",
"pId": "id21343123",
"pLogUrl": "https://image.xxxx.com/yyy.png",
"incentiv": "3p1",
"details": {
"tUrl": "https://url.here.com/",
"desc": "textHere11",
"juToSUrl": "http://surl.com/",
"juToSBut": "shop"
}
},
{
"sName": "weh",
"lName": "wehii",
"pId": "id56569653",
"pLogUrl": "https://image.xxxx.com/yyy.png",
"incentiv": "3p221",
"details": {
"tUrl": "https://url.here.com/",
"desc": "textHere11",
"juToSUrl": "http://surl.com/",
"juToSBut": "shop"
}
}
]
}
And the html is exactly the same as above (of course just the id is not the same), for the one getting the data from mysql (with php)

i think this link can help you =):
https://editor.datatables.net/examples/advanced/REST.html

Related

Adding DropDown list in jQuery DataTable

I want to display table's data with jQuery DataTable and sometimes apply an extra data filtering, using the output of a dropdown select input.
The main code for fetching data (fetch.php) is:
<?php
include('db.php');
include('function.php');
$query = '';
$output = array();
$query .= "SELECT * FROM Part_tb ";
if(isset($_POST["search"]["value"]))
{
$query .= 'WHERE part_manufacturer LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR part_id LIKE "%'.$_POST["search"]["value"].'%" ';
}
if(isset($_POST["order"]))
{
$query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
}
else
{
$query .= 'ORDER BY part_id ASC ';
}
if($_POST["length"] != -1)
{
$query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$statement = $connection->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
$filtered_rows = $statement->rowCount();
foreach($result as $row)
{
$sub_array = array();
$sub_array[] = $row["part_manufacturer"];
$sub_array[] = $row["part_id"];
$sub_array[] = $row["part_category"];
$sub_array[] = $row["part_stock"];
$data[] = $sub_array;
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => $filtered_rows,
"recordsFiltered" => get_total_all_records(),
"data" => $data
);
echo json_encode($output);
?>
while the DataTable is defined in index.php as follows:
var dataTable = $('#user_data').DataTable({
"processing":true,
"serverSide":true,
"order":[],
"ajax":{
url:"actions/fetch.php",
type:"POST"
},
"columnDefs":[
{
"targets":[0, 1],
"orderable":false,
},
],
});
In index.php, i've created 3 dependent dropdown lists, which load data from other tables. Now, i want to take the id of 3rd dropdown list and update the data of Part_tb in fetch.php accordingly. Below, you can see that when 3rd dropdown change, i call a function load_parts():
$(document).on('change', '#sub3_category_item', function(){
load_parts();
});
function load_parts()
{
var action = 'fetch_data';
var filter_part_id = $('#sub2_category_item').val();
$.ajax({
url:"actions/fetch.php",
method:"post",
data:{action:action, filter_part_id:filter_part_id},
success:function(data)
{
$('#user_data').DataTable().ajax.reload();
}
});
}
The problem is that i can't filter the data of fetch.php according to the selected id of #sub2_category_item. Could you help me on that?
I've modified the index.php as follows:
$(document).on('change', '#sub3_category_item', function(){
var filter_part_id = $('#sub3_category_item').val();
$('#user_data').DataTable().destroy();
fill_datatable(filter_part_id);
});
fill_datatable();
function fill_datatable(filter_part_id = '')
{
var dataTable = $('#user_data').DataTable({
"processing":true,
"serverSide":true,
"order":[],
"searching" : false,
"ajax":{
url:"actions/fetch.php",
type:"POST",
data:{filter_part_id:filter_part_id}
}
});
and fetch.php:
$query .= "SELECT * FROM Part_tb ";
if(isset($_POST['filter_part_id']) && $_POST['filter_part_id'] != '')
{
$query .= "SELECT * FROM Part_tb WHERE part_id IN (SELECT pcfit_name from Part_car_fit_tb WHERE pcfit_id ='".$_POST["filter_part_id"]."') ";
}
but dataTable crashes, when #sub3_category_item is selected. Any idea, how to filter datatable with the value $_POST["filter_part_id"]?

(Codeigniter) jQuery datatable server-side processing with sql server

i have an issue with jQuery datatables i want to use server-side processing, because to much data to load. but from the documentation i have read it use native php, i use codeigniter 3. it quite difficult to modify the code. here's the code i use in my controller
public function dataTable()
{
$sIndexColumn = "";
$sTable = "myTable";
$gaSql['user'] = "test";
$gaSql['password'] = "t3st";
$gaSql['db'] = "myDatabase";
$gaSql['server'] = "Driver={SQL Server Native Client 10.0};Server=ITI-0299-PC\JTSMSSQLSERVER;Port=1326;Database=myDatabase; Uid=test;Pwd=t3st;"; //Locale
$aColumns = array(
'id','nmrumahsakit','alamat','kota',
'provinsi','rawat_inap','rawat_jalan',
'mcu','telp','fax','latitude',
'longitude','created_at','updated_at');
/*
* ODBC connection
*/
$connectionInfo = array("UID" => $gaSql['user'], "PWD" => $gaSql['password'], "Database"=>$gaSql['db'],"ReturnDatesAsStrings"=>true);
$gaSql['link'] = sqlsrv_connect( $gaSql['server'], $connectionInfo);
$params = array();
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
/* Ordering */
$sOrder = "";
if ( isset( $_GET['iSortCol_0'] ) ) {
$sOrder = "ORDER BY id ";
for ( $i=0 ; $i<intval( $_GET['iSortingCols'] ) ; $i++ ) {
if ( $_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" ) {
$sOrder .= $aColumns[ intval( $_GET['iSortCol_'.$i] ) ]."
".addslashes( $_GET['sSortDir_'.$i] ) .", ";
}
}
$sOrder = substr_replace( $sOrder, "", -2 );
if ( $sOrder == "ORDER BY id" ) {
$sOrder = "";
}
}
/* Filtering */
$sWhere = "";
if ( isset($_GET['sSearch']) && $_GET['sSearch'] != "" ) {
$sWhere = "WHERE (";
for ( $i=0 ; $i<count($aColumns) ; $i++ ) {
$sWhere .= $aColumns[$i]." LIKE '%".addslashes( $_GET['sSearch'] )."%' OR ";
}
$sWhere = substr_replace( $sWhere, "", -3 );
$sWhere .= ')';
}
/* Individual column filtering */
for ( $i=0 ; $i<count($aColumns) ; $i++ ) {
if ( isset($_GET['bSearchable_'.$i]) && $_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != '' ) {
if ( $sWhere == "" ) {
$sWhere = "WHERE ";
} else {
$sWhere .= " AND ";
}
$sWhere .= $aColumns[$i]." LIKE '%".addslashes($_GET['sSearch_'.$i])."%' ";
}
}
/* Paging */
$top = (isset($_GET['iDisplayStart']))?((int)$_GET['iDisplayStart']):0 ;
$limit = (isset($_GET['iDisplayLength']))?((int)$_GET['iDisplayLength'] ):10;
$sQuery = "SELECT TOP $limit ".implode(",",$aColumns)."
FROM $sTable
$sWhere ".(($sWhere=="")?" WHERE ":" AND ")." $sIndexColumn NOT IN
(
SELECT $sIndexColumn FROM
(
SELECT TOP $top ".implode(",",$aColumns)."
FROM $sTable
$sWhere
$sOrder
)
as [virtTable]
)
$sOrder";
$rResult = sqlsrv_query($gaSql['link'],$sQuery) or die("$sQuery: " . sqlsrv_errors());
$sQueryCnt = "SELECT * FROM $sTable $sWhere";
$rResultCnt = sqlsrv_query( $gaSql['link'], $sQueryCnt ,$params, $options) or die (" $sQueryCnt: " . sqlsrv_errors());
$iFilteredTotal = sqlsrv_num_rows( $rResultCnt );
$sQuery = " SELECT * FROM $sTable ";
$rResultTotal = sqlsrv_query( $gaSql['link'], $sQuery ,$params, $options) or die(sqlsrv_errors());
$iTotal = sqlsrv_num_rows( $rResultTotal );
$output = array(
"sEcho" => intval($_GET['sEcho']),
"iTotalRecords" => $iTotal,
"iTotalDisplayRecords" => $iFilteredTotal,
"aaData" => array()
);
while ( $aRow = sqlsrv_fetch_array( $rResult ) ) {
$row = array();
for ( $i=0 ; $i<count($aColumns) ; $i++ ) {
if ( $aColumns[$i] != ' ' ) {
$v = $aRow[ $aColumns[$i] ];
$v = mb_check_encoding($v, 'UTF-8') ? $v : utf8_encode($v);
$row[]=$v;
}
}
If (!empty($row)) { $output['aaData'][] = $row; }
}
echo json_encode( $output );
}
in this is js configuration for datatables:
$('#datatable2').dataTable({
"sScrollY": "400px",
"bProcessing": true,
"bServerSide": true,
"sServerMethod": "GET",
"sAjaxSource": "<?php echo base_url(); ?>mycontroller/mymethod",
"iDisplayLength": 10,
"aLengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
"aaSorting": [[0, 'asc']],
"aoColumns": [
{ "bVisible": true, "bSearchable": true, "bSortable": true },
{ "bVisible": true, "bSearchable": true, "bSortable": true },
{ "bVisible": true, "bSearchable": true, "bSortable": true }
]
}).fnSetFilteringDelay(700);
});
and this is the view:
<table id="datatable2" class="table table-bordered table-hover">
<thead>
<tr>
<th>No</th>
<th>Nama R.S</th>
<th>Alamat</th>
<th>Kota</th>
<th>Provinsi</th>
<th>Rawat Inap</th>
<th>Rawat Jalan</th>
<th>MCU</th>
<th>No.Telp</th>
<th>No.Fax</th>
<th>Latitude</th>
<th>Longitude</th>
<th>Created At</th>
<th>Updated At</th>
<th>Menu</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
after test it, ive got this error.
A PHP Error was encountered
Severity: Error
Message: Call to undefined function sqlsrv_connect()
Filename: controllers/Provider.php
Line Number: 302
Backtrace:
I already use connection in config/database.php
and my question is how to user server-side processing in codeigniter?
Problem above solve, but i've got new problem with js.
DataTables warning (table id = 'datatable2'): DataTables warning: JSON
data from server could not be parsed. This is caused by a JSON
formatting error.
CMIIW
It seems that your PHP installation is missing an extension that allows you to use the sqlsrv_connect function.
Make sure that php_sqlsrv_XX_ts.dll extension is loaded in your php.ini.

How can I fix the Image horizontal reel scroll slideshow images being stacked vertically?

The images (logos) are for some reason showing up stacked vertically using this plugin: Image horizontal reel scroll slideshow
https://wordpress.org/support/plugin/image-horizontal-reel-scroll-slideshow
You can see the behavior near the bottom of this page where the sponsors are located: http://tinyurl.com/phu86z9
I've tried re-installing the plugin and changing the type setting. Nothing has fixed this problem.
This is the shortcode I'm using to insert into the page:
[ihrss-gallery type="WIDGET" w="940" h="170" speed="3" bgcolor="#FFFFFF" gap="5" random="NO"]
There's actually 4 or 5 logos (even though you'll see the same one repeated twice at first glance), the div cuts them off with overflow: hidden, so they're hidden right now.
If you look for this div:
<div style="position:relative;width:940px;height: 170px;overflow:hidden">
and increase the height to 500px in chrome developer tools, you'll see what I mean.
How can I fix this so that the images line up horizontally as they're supposed to? I would also accept an answer that points me to another plugin that provides the same functionality.
It seems plugin needed some modifications. Codes are below.
image-horizontal-reel-scroll-slideshow.js
/**
* Image horizontal reel scroll slideshow
* Copyright (C) 2011 - 2014 www.gopiplus.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
var copyspeed=IHRSS_SPEED
IHRSS_SLIDESRARRAY='<nobr><ul style="list-style:none">'+IHRSS_SLIDESRARRAY.join(IHRSS_IMGGAP)+'</ul></nobr>'
var iedom=document.all||document.getElementById
if (iedom)
document.write('<span id="temp" style="visibility:hidden;position:absolute;top:-100px;left:-9000px">'+IHRSS_SLIDESRARRAY+'</span>')
var actualwidth=''
var cross_slide, ns_slide
function fillup(){
if (iedom){
cross_slide=document.getElementById? document.getElementById("test2") : document.all.test2
cross_slide2=document.getElementById? document.getElementById("test3") : document.all.test3
cross_slide.innerHTML=cross_slide2.innerHTML=IHRSS_SLIDESRARRAY
actualwidth=document.all? cross_slide.offsetWidth : document.getElementById("temp").offsetWidth
cross_slide2.style.left=actualwidth+IHRSS_PIXELGAP+"px"
}
else if (document.layers){
ns_slide=document.ns_slidemenu.document.ns_slidemenu2
ns_slide2=document.ns_slidemenu.document.ns_slidemenu3
ns_slide.document.write(IHRSS_SLIDESRARRAY)
ns_slide.document.close()
actualwidth=ns_slide.document.width
ns_slide2.left=actualwidth+IHRSS_PIXELGAP
ns_slide2.document.write(IHRSS_SLIDESRARRAY)
ns_slide2.document.close()
}
lefttime=setInterval("slideleft()",30)
}
window.onload=fillup
function slideleft(){
if (iedom){
if (parseInt(cross_slide.style.left)>(actualwidth*(-1)+8))
cross_slide.style.left=parseInt(cross_slide.style.left)-copyspeed+"px"
else
cross_slide.style.left=parseInt(cross_slide2.style.left)+actualwidth+IHRSS_PIXELGAP+"px"
if (parseInt(cross_slide2.style.left)>(actualwidth*(-1)+8))
cross_slide2.style.left=parseInt(cross_slide2.style.left)-copyspeed+"px"
else
cross_slide2.style.left=parseInt(cross_slide.style.left)+actualwidth+IHRSS_PIXELGAP+"px"
}
else if (document.layers){
if (ns_slide.left>(actualwidth*(-1)+8))
ns_slide.left-=copyspeed
else
ns_slide.left=ns_slide2.left+actualwidth+IHRSS_PIXELGAP
if (ns_slide2.left>(actualwidth*(-1)+8))
ns_slide2.left-=copyspeed
else
ns_slide2.left=ns_slide.left+actualwidth+IHRSS_PIXELGAP
}
}
if (iedom||document.layers){
with (document){
document.write('<table border="0" cellspacing="0" cellpadding="0"><td>')
if (iedom){
write('<div style="position:relative;width:'+IHRSS_WIDTH+';height:'+IHRSS_HEIGHT+';overflow:hidden">')
write('<div style="position:absolute;width:'+IHRSS_WIDTH+';height:'+IHRSS_HEIGHT+';background-color:'+IHRSS_BGCOLOR+'" onMouseover="copyspeed=0" onMouseout="copyspeed=IHRSS_SPEED">')
write('<div id="test2" style="position:absolute;left:0px;top:0px"></div>')
write('<div id="test3" style="position:absolute;left:-1000px;top:0px"></div>')
write('</div></div>')
}
else if (document.layers){
write('<ilayer width='+IHRSS_WIDTH+' height='+IHRSS_HEIGHT+' name="ns_slidemenu" bgColor='+IHRSS_BGCOLOR+'>')
write('<layer name="ns_slidemenu2" left=0 top=0 onMouseover="copyspeed=0" onMouseout="copyspeed=IHRSS_SPEED"></layer>')
write('<layer name="ns_slidemenu3" left=0 top=0 onMouseover="copyspeed=0" onMouseout="copyspeed=IHRSS_SPEED"></layer>')
write('</ilayer>')
}
document.write('</td></table>')
}
}
i added ul tag inside nobr tag at line 20
image-horizontal-reel-scroll-slideshow.php
<?php
/*
Plugin Name: Image horizontal reel scroll slideshow
Plugin URI: http://www.gopiplus.com/work/2011/05/08/wordpress-plugin-image-horizontal-reel-scroll-slideshow/
Description: Image horizontal reel scroll slideshow lets showcase images in a horizontal move style. This slideshow will pause on mouse over. The speed of the plugin gallery is customizable.
Author: Gopi Ramasamy
Version: 11.6
Author URI: http://www.gopiplus.com/work/2011/05/08/wordpress-plugin-image-horizontal-reel-scroll-slideshow/
Donate link: http://www.gopiplus.com/work/2011/05/08/wordpress-plugin-image-horizontal-reel-scroll-slideshow/
Tags: Horizontal, Image, Reel, Scroll, Slideshow, Gallery
License: GPLv2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
*/
global $wpdb, $wp_version;
define("WP_Ihrss_TABLE", $wpdb->prefix . "Ihrss_plugin");
define("WP_Ihrss_UNIQUE_NAME", "Ihrss");
define('WP_Ihrss_FAV', 'http://www.gopiplus.com/work/2011/05/08/wordpress-plugin-image-horizontal-reel-scroll-slideshow/');
if ( ! defined( 'WP_IHRSS_BASENAME' ) )
define( 'WP_IHRSS_BASENAME', plugin_basename( __FILE__ ) );
if ( ! defined( 'WP_IHRSS_PLUGIN_NAME' ) )
define( 'WP_IHRSS_PLUGIN_NAME', trim( dirname( WP_IHRSS_BASENAME ), '/' ) );
if ( ! defined( 'WP_IHRSS_PLUGIN_URL' ) )
define( 'WP_IHRSS_PLUGIN_URL', WP_PLUGIN_URL . '/' . WP_IHRSS_PLUGIN_NAME );
if ( ! defined( 'WP_IHRSS_ADMIN_URL' ) )
define( 'WP_IHRSS_ADMIN_URL', get_option('siteurl') . '/wp-admin/options-general.php?page=image-horizontal-reel-scroll-slideshow' );
function Ihrss()
{
global $wpdb;
$Ihrss_package = "";
$Ihrss_title = get_option('Ihrss_title');
$Ihrss_sliderwidth = get_option('Ihrss_sliderwidth');
$Ihrss_sliderheight = get_option('Ihrss_sliderheight');
$Ihrss_slidespeed = get_option('Ihrss_slidespeed');
$Ihrss_slidebgcolor = get_option('Ihrss_slidebgcolor');
$Ihrss_slideshowgap = get_option('Ihrss_slideshowgap');
$Ihrss_random = get_option('Ihrss_random');
$Ihrss_type = get_option('Ihrss_type');
if(!is_numeric($Ihrss_sliderwidth)) { $Ihrss_sliderwidth = 500; }
if(!is_numeric($Ihrss_sliderheight)) { $Ihrss_sliderheight = 170; }
if(!is_numeric($Ihrss_slidespeed)) { $Ihrss_slidespeed = 1; }
if(!is_numeric($Ihrss_slideshowgap)) { $Ihrss_slideshowgap = 5; }
$Ihrss_slideshowgaphtml = "padding-right:".$Ihrss_slideshowgap."px;";
$sSql = "select Ihrss_path,Ihrss_link,Ihrss_target,Ihrss_title from ".WP_Ihrss_TABLE." where 1=1";
if($Ihrss_type <> ""){ $sSql = $sSql . " and Ihrss_type='".$Ihrss_type."'"; }
if($Ihrss_random == "YES"){ $sSql = $sSql . " ORDER BY RAND()"; }else{ $sSql = $sSql . " ORDER BY Ihrss_order"; }
$data = $wpdb->get_results($sSql);
$cnt = 0;
if ( ! empty($data) )
{
foreach ( $data as $data )
{
$Ihrss_path = trim($data->Ihrss_path);
$Ihrss_link = trim($data->Ihrss_link);
$Ihrss_target = trim($data->Ihrss_target);
$Ihrss_title = trim($data->Ihrss_title);
$Ihrss_package = $Ihrss_package ."IHRSS_SLIDESRARRAY[$cnt]='<li style=\"display:inline-block;\"><a style=\"$Ihrss_slideshowgaphtml\" title=\"$Ihrss_title\" target=\"$Ihrss_target\" href=\"$Ihrss_link\"><img alt=\"$Ihrss_title\" src=\"$Ihrss_path\" /></a></li>'; ";
$cnt++;
}
?>
<script language="JavaScript1.2">
var IHRSS_WIDTH = "<?php echo $Ihrss_sliderwidth."px"; ?>";
var IHRSS_HEIGHT = "<?php echo $Ihrss_sliderheight."px"; ?>";
var IHRSS_SPEED = <?php echo $Ihrss_slidespeed; ?>;
IHRSS_BGCOLOR = "<?php echo $Ihrss_slidebgcolor; ?>";
var IHRSS_SLIDESRARRAY=new Array();
var IHRSS_FINALSLIDE ='';
<?php echo $Ihrss_package; ?>
var IHRSS_IMGGAP = " ";
var IHRSS_PIXELGAP = 1;
</script>
<script language="JavaScript1.2" src="<?php echo WP_IHRSS_PLUGIN_URL; ?>/image-horizontal-reel-scroll-slideshow.js"></script>
<?php
}
else
{
_e('No images available in this Gallery Type. Please check admin setting.', 'ihrss');;
}
}
function Ihrss_install()
{
global $wpdb;
if($wpdb->get_var("show tables like '". WP_Ihrss_TABLE . "'") != WP_Ihrss_TABLE)
{
$sSql = "CREATE TABLE IF NOT EXISTS ". WP_Ihrss_TABLE . " (";
$sSql = $sSql . "Ihrss_id INT NOT NULL AUTO_INCREMENT ,";
$sSql = $sSql . "Ihrss_path TEXT CHARACTER SET utf8 COLLATE utf8_bin NOT NULL ,";
$sSql = $sSql . "Ihrss_link TEXT CHARACTER SET utf8 COLLATE utf8_bin NOT NULL ,";
$sSql = $sSql . "Ihrss_target VARCHAR( 50 ) NOT NULL ,";
$sSql = $sSql . "Ihrss_title VARCHAR( 500 ) NOT NULL ,";
$sSql = $sSql . "Ihrss_order INT NOT NULL ,";
$sSql = $sSql . "Ihrss_status VARCHAR( 10 ) NOT NULL ,";
$sSql = $sSql . "Ihrss_type VARCHAR( 100 ) NOT NULL ,";
$sSql = $sSql . "Ihrss_extra1 VARCHAR( 100 ) NOT NULL ,";
$sSql = $sSql . "Ihrss_extra2 VARCHAR( 100 ) NOT NULL ,";
$sSql = $sSql . "Ihrss_date datetime NOT NULL default '0000-00-00 00:00:00' ,";
$sSql = $sSql . "PRIMARY KEY ( Ihrss_id )";
$sSql = $sSql . ") ENGINE=MyISAM DEFAULT CHARSET=utf8;";
$wpdb->query($sSql);
$IsSql = "INSERT INTO `". WP_Ihrss_TABLE . "` (`Ihrss_path`, `Ihrss_link`, `Ihrss_target` , `Ihrss_title` , `Ihrss_order` , `Ihrss_status` , `Ihrss_type` , `Ihrss_date`)";
$sSql = $IsSql . " VALUES ('".get_option('siteurl')."/wp-content/plugins/image-horizontal-reel-scroll-slideshow/images/Sing_1.jpg', '#', '_blank', 'Image 1', '1', 'YES', 'GROUP1', '0000-00-00 00:00:00');";
$wpdb->query($sSql);
$sSql = $IsSql . " VALUES ('".get_option('siteurl')."/wp-content/plugins/image-horizontal-reel-scroll-slideshow/images/Sing_2.jpg' ,'#', '_blank', 'Image 2', '2', 'YES', 'GROUP1', '0000-00-00 00:00:00');";
$wpdb->query($sSql);
$sSql = $IsSql . " VALUES ('".get_option('siteurl')."/wp-content/plugins/image-horizontal-reel-scroll-slideshow/images/Sing_3.jpg', '#', '_blank', 'Image 3', '1', 'YES', 'Widget', '0000-00-00 00:00:00');";
$wpdb->query($sSql);
$sSql = $IsSql . " VALUES ('".get_option('siteurl')."/wp-content/plugins/image-horizontal-reel-scroll-slideshow/images/Sing_4.jpg', '#', '_blank', 'Image 4', '2', 'YES', 'Widget', '0000-00-00 00:00:00');";
$wpdb->query($sSql);
}
add_option('Ihrss_title', "Horizontal Slideshow");
add_option('Ihrss_sliderwidth', "400");
add_option('Ihrss_sliderheight', "75");
add_option('Ihrss_slidespeed', "1");
add_option('Ihrss_slidebgcolor', "#ffffff");
add_option('Ihrss_slideshowgap', "10");
add_option('Ihrss_random', "YES");
add_option('Ihrss_type', "Widget");
}
function Ihrss_control()
{
echo '<p><b>';
_e('Image horizontal reel scroll slideshow', 'ihrss');
echo '.</b> ';
_e('Check official website for more information', 'ihrss');
?> <a target="_blank" href="<?php echo WP_Ihrss_FAV; ?>"><?php _e('click here', 'ihrss'); ?></a></p><?php
}
function Ihrss_widget($args)
{
extract($args);
echo $before_widget . $before_title;
echo get_option('Ihrss_Title');
echo $after_title;
Ihrss();
echo $after_widget;
}
function Ihrss_admin_options()
{
global $wpdb;
$current_page = isset($_GET['ac']) ? $_GET['ac'] : '';
switch($current_page)
{
case 'edit':
include('pages/image-management-edit.php');
break;
case 'add':
include('pages/image-management-add.php');
break;
case 'set':
include('pages/image-setting.php');
break;
default:
include('pages/image-management-show.php');
break;
}
}
add_shortcode( 'ihrss-gallery', 'Ihrss_shortcode' );
function Ihrss_shortcode( $atts )
{
global $wpdb;
$Ihrss = "";
$Ihrss_package = "";
// New code
//[ihrss-gallery type="Widget" w="600" h="170" speed="1" bgcolor="#FFFFFF" gap="10" random="YES"]
if ( ! is_array( $atts ) ) { return ''; }
$Ihrss_type = $atts['type'];
$Ihrss_sliderwidth = $atts['w'];
$Ihrss_sliderheight = $atts['h'];
$Ihrss_slidespeed = $atts['speed'];
$Ihrss_slidebgcolor = $atts['bgcolor'];
$Ihrss_slideshowgap = $atts['gap'];
$Ihrss_random = $atts['random'];
if(!is_numeric($Ihrss_sliderwidth)) { $Ihrss_sliderwidth = 250 ;}
if(!is_numeric($Ihrss_sliderheight)) { $Ihrss_sliderheight = 200; }
if(!is_numeric($Ihrss_slidespeed)) { $Ihrss_slidespeed = 1; }
if(!is_numeric($Ihrss_slideshowgap)) { $Ihrss_slideshowgap = 5; }
$Ihrss_slideshowgaphtml = "padding-right:".$Ihrss_slideshowgap."px;";
$sSql = "select Ihrss_path,Ihrss_link,Ihrss_target,Ihrss_title from ".WP_Ihrss_TABLE." where 1=1";
if($Ihrss_type <> ""){ $sSql = $sSql . " and Ihrss_type='".$Ihrss_type."'"; }
if($Ihrss_random == "YES"){ $sSql = $sSql . " ORDER BY RAND()"; }else{ $sSql = $sSql . " ORDER BY Ihrss_order"; }
$data = $wpdb->get_results($sSql);
$cnt = 0;
if ( ! empty($data) )
{
foreach ( $data as $data )
{
$Ihrss_path = trim($data->Ihrss_path);
$Ihrss_link = trim($data->Ihrss_link);
$Ihrss_target = trim($data->Ihrss_target);
$Ihrss_title = trim($data->Ihrss_title);
$Ihrss_package = $Ihrss_package ."IHRSS_SLIDESRARRAY[$cnt]='<li style=\"display:inline-block;\"><a style=\"$Ihrss_slideshowgaphtml\" title=\"$Ihrss_title\" target=\"$Ihrss_target\" href=\"$Ihrss_link\"><img alt=\"$Ihrss_title\" src=\"$Ihrss_path\" /></a></li>'; ";
$cnt++;
}
$Ihrss_pluginurl = get_option('siteurl') . "/wp-content/plugins/image-horizontal-reel-scroll-slideshow/";
$Ihrss = $Ihrss .'<script language="JavaScript1.2">';
$Ihrss = $Ihrss .'var IHRSS_WIDTH = "'.$Ihrss_sliderwidth.'px"; ';
$Ihrss = $Ihrss .'var IHRSS_HEIGHT = "'.$Ihrss_sliderheight.'px"; ';
$Ihrss = $Ihrss .'var IHRSS_SPEED = '. $Ihrss_slidespeed.'; ';
$Ihrss = $Ihrss .'var IHRSS_BGCOLOR = "'.$Ihrss_slidebgcolor.'"; ';
$Ihrss = $Ihrss .'var IHRSS_SLIDESRARRAY=new Array(); ';
$Ihrss = $Ihrss .'var IHRSS_FINALSLIDE =" "; ';
$Ihrss = $Ihrss .$Ihrss_package;
$Ihrss = $Ihrss .'var IHRSS_IMGGAP = " "; ';
$Ihrss = $Ihrss .'var IHRSS_PIXELGAP = 1; ';
$Ihrss = $Ihrss .'</script>';
$Ihrss = $Ihrss .'<script language="JavaScript1.2" src="'.$Ihrss_pluginurl.'/image-horizontal-reel-scroll-slideshow.js"></script>';
}
else
{
$Ihrss = $Ihrss . __('No images available in this Gallery Type. Please check admin setting.', 'ihrss');
}
return $Ihrss;
}
function Ihrss_add_to_menu()
{
if (is_admin())
{
add_options_page(__('Image horizontal reel scroll slideshow', 'ihrss'),
__('Image horizontal reel scroll slideshow', 'ihrss'), 'manage_options', "image-horizontal-reel-scroll-slideshow", 'Ihrss_admin_options' );
}
}
function Ihrss_init()
{
if(function_exists('wp_register_sidebar_widget'))
{
wp_register_sidebar_widget('Image-horizontal-reel-scroll-slideshow', __('Image horizontal reel scroll slideshow', 'ihrss'), 'Ihrss_widget');
}
if(function_exists('wp_register_widget_control'))
{
wp_register_widget_control('Image-horizontal-reel-scroll-slideshow', array(__('Image horizontal reel scroll slideshow', 'ihrss'), 'widgets'), 'Ihrss_control');
}
}
function Ihrss_deactivation()
{
// No action required.
}
function Ihrss_textdomain()
{
load_plugin_textdomain( 'ihrss', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
}
add_action('plugins_loaded', 'Ihrss_textdomain');
add_action('admin_menu', 'Ihrss_add_to_menu');
add_action("plugins_loaded", "Ihrss_init");
register_activation_hook(__FILE__, 'Ihrss_install');
register_deactivation_hook(__FILE__, 'Ihrss_deactivation');
?>
i wrapped a tag with li tag at lines 67 and 219
I hope this will fix your issue. It worked well for me.
I try to modify
http://dev.lhpssa.org/wp-content/plugins/image-horizontal-reel-scroll-slideshow//image-horizontal-reel-scroll-slideshow.js
and combine with inline call
<script type="text/javascript">
var IHRSS_WIDTH = "940px";
var IHRSS_HEIGHT = "170px";
var IHRSS_SPEED = 3;
var IHRSS_BGCOLOR = "#FFFFFF";
var IHRSS_SLIDESRARRAY=new Array();
var IHRSS_FINALSLIDE =" ";
IHRSS_SLIDESRARRAY[0]='<a style="float:left;padding-right:5px;width25px;" title="Antique Reels" target="_blank" href="http://www.antiquereels.com/tomgreene/index.html"><img alt="Antique Reels" src="http://dev.lhpssa.org/wp-content/uploads/2013/07/customrodandreel.jpg" /></a>';
IHRSS_SLIDESRARRAY[1]='<a style="float:left;padding-right:5px;width25px;" title="Holy Cross Ortho" target="_blank" href="http://www.holy-cross.com/orthopaedics/kleinhenz.php"><img alt="Holy Cross Ortho" src="http://dev.lhpssa.org/wp-content/uploads/2013/07/holycrosshospital.jpg" /></a>';
IHRSS_SLIDESRARRAY[2]='<a style="float:left;padding-right:5px;width25px;" title="Holy Cross Hospital" target="_blank" href="http://www.holy-cross.com/orthopaedics/kleinhenz.php"><img alt="Holy Cross Hospital" src="http://dev.lhpssa.org/wp-content/uploads/2013/07/tracysands.jpg" /></a>';
IHRSS_SLIDESRARRAY[3]='<a style="float:left;padding-right:5px;width25px;" title="Re/Max" target="_blank" href="http://www.southfloridahouses.net"><img alt="Re/Max" src="http://dev.lhpssa.org/wp-content/uploads/2014/01/Screen-Shot-2014-01-09-at-4.05.50-PM.png" /></a>';
var IHRSS_IMGGAP = " ";
var IHRSS_PIXELGAP = 1;
var copyspeed=IHRSS_SPEED
IHRSS_SLIDESRARRAY=IHRSS_SLIDESRARRAY.join(IHRSS_IMGGAP)
var iedom=document.all||document.getElementById
if (iedom)
document.write('<span id="temp" style="visibility:hidden;position:absolute;top:-100px;left:-9000px">'+IHRSS_SLIDESRARRAY+'</span>')
var actualwidth=''
var cross_slide, ns_slide
function fillup(){
if (iedom){
cross_slide=document.getElementById? document.getElementById("test2") : document.all.test2
cross_slide2=document.getElementById? document.getElementById("test3") : document.all.test3
cross_slide.innerHTML=cross_slide2.innerHTML=IHRSS_SLIDESRARRAY
actualwidth=document.all? cross_slide.offsetWidth : document.getElementById("temp").offsetWidth
cross_slide2.style.left=actualwidth+IHRSS_PIXELGAP+"px"
}
else if (document.layers){
ns_slide=document.ns_slidemenu.document.ns_slidemenu2
ns_slide2=document.ns_slidemenu.document.ns_slidemenu3
ns_slide.document.write(IHRSS_SLIDESRARRAY)
ns_slide.document.close()
actualwidth=ns_slide.document.width
ns_slide2.left=actualwidth+IHRSS_PIXELGAP
ns_slide2.document.write(IHRSS_SLIDESRARRAY)
ns_slide2.document.close()
}
lefttime=setInterval("slideleft()",30)
}
window.onload=fillup
function slideleft(){
if (iedom){
if (parseInt(cross_slide.style.left)>(actualwidth*(-1)+8))
cross_slide.style.left=parseInt(cross_slide.style.left)-copyspeed+"px"
else
cross_slide.style.left=parseInt(cross_slide2.style.left)+actualwidth+IHRSS_PIXELGAP+"px"
if (parseInt(cross_slide2.style.left)>(actualwidth*(-1)+8))
cross_slide2.style.left=parseInt(cross_slide2.style.left)-copyspeed+"px"
else
cross_slide2.style.left=parseInt(cross_slide.style.left)+actualwidth+IHRSS_PIXELGAP+"px"
}
else if (document.layers){
if (ns_slide.left>(actualwidth*(-1)+8))
ns_slide.left-=copyspeed
else
ns_slide.left=ns_slide2.left+actualwidth+IHRSS_PIXELGAP
if (ns_slide2.left>(actualwidth*(-1)+8))
ns_slide2.left-=copyspeed
else
ns_slide2.left=ns_slide.left+actualwidth+IHRSS_PIXELGAP
}
}
if (iedom||document.layers){
with (document){
document.write('<table border="0" cellspacing="0" cellpadding="0"><td>')
if (iedom){
write('<div style="position:relative;width:'+IHRSS_WIDTH+';height:'+IHRSS_HEIGHT+';overflow:hidden">')
write('<div style="position:absolute;width:'+IHRSS_WIDTH+';height:'+IHRSS_HEIGHT+';background-color:'+IHRSS_BGCOLOR+'" onMouseover="copyspeed=0" onMouseout="copyspeed=IHRSS_SPEED">')
write('<div id="test2" style="float:left;position:absolute;left:0px;top:0px;width:1400px;"></div>')
write('<div id="test3" style="float:left;position:absolute;left:-1000px;top:0px;width:1400px;"></div>')
write('</div></div>')
}
else if (document.layers){
write('<ilayer width='+IHRSS_WIDTH+' height='+IHRSS_HEIGHT+' name="ns_slidemenu" bgColor='+IHRSS_BGCOLOR+'>')
write('<layer name="ns_slidemenu2" left=0 top=0 onMouseover="copyspeed=0" onMouseout="copyspeed=IHRSS_SPEED"></layer>')
write('<layer name="ns_slidemenu3" left=0 top=0 onMouseover="copyspeed=0" onMouseout="copyspeed=IHRSS_SPEED"></layer>')
write('</ilayer>')
}
document.write('</td></table>')
}
}
</script>
Output:

How to make codnitive sidenav slide up/down?

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&REG;</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

Getting buddypress user name in a javascript file

From within my buddypress PHP templates I usually get the username of any given user by referencing the user ID like this:-
<?php echo bp_core_get_username( '{{userID}}' ) ?>
However I need to retrieve the username from within an external Javascript file.
The user ID is already passed in as var aData[11]. I have tried the following with no luck:-
$('td:eq(3)', nRow).html( '<div class="table-row"><h4 class="nomargin">' + aData[0] + '</h4>' + aData[1] + '</div>' );
I am trying to return a URL... This cirrently gives me:
http://www.mysite.com/members//song/?songsID=6
Whe it should be:
http://www.mysite.com/members/username/song/?songsID=6
Any ideas?
Edit: Below is the server side code that I am using to ouput the JSON
<?php
$aColumns = array( 'song_name', 'artist_band_name', 'author', 'song_artwork', 'song_file', 'genre', 'song_description', 'uploaded_time', 'emotion', 'tempo', 'songsID', 'user' );
$sIndexColumn = "songsID";
/* DB table to use */
$sTable = "wp_dbt_songs";
/* Database connection information */
$gaSql['user'] = "";
$gaSql['password'] = "";
$gaSql['db'] = "";
$gaSql['server'] = "";
$gaSql['link'] = mysql_pconnect( $gaSql['server'], $gaSql['user'], $gaSql['password'] ) or
die( 'Could not open connection to server' );
mysql_select_db( $gaSql['db'], $gaSql['link'] ) or
die( 'Could not select database '. $gaSql['db'] );
$sLimit = "";
if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' )
{
$sLimit = "LIMIT ".mysql_real_escape_string( $_GET['iDisplayStart'] ).", ".
mysql_real_escape_string( $_GET['iDisplayLength'] );
}
if ( isset( $_GET['iSortCol_0'] ) )
{
$sOrder = "ORDER BY ";
for ( $i=0 ; $i<intval( $_GET['iSortingCols'] ) ; $i++ )
{
if ( $_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" )
{
$sOrder .= $aColumns[ intval( $_GET['iSortCol_'.$i] ) ]."
".mysql_real_escape_string( $_GET['sSortDir_'.$i] ) .", ";
}
}
$sOrder = substr_replace( $sOrder, "", -2 );
if ( $sOrder == "ORDER BY" )
{
$sOrder = "";
}
}
$sWhere = "";
if ( $_GET['sSearch'] != "" )
{
$sWhere = "WHERE (";
for ( $i=0 ; $i<count($aColumns) ; $i++ )
{
$sWhere .= $aColumns[$i]." LIKE '%".mysql_real_escape_string( $_GET['sSearch'] )."%' OR ";
}
$sWhere = substr_replace( $sWhere, "", -3 );
$sWhere .= ')';
}
/* Individual column filtering */
for ( $i=0 ; $i<count($aColumns) ; $i++ )
{
if ( $_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != '' )
{
if ( $sWhere == "" )
{
$sWhere = "WHERE ";
}
else
{
$sWhere .= " AND ";
}
$sWhere .= $aColumns[$i]." LIKE '%".mysql_real_escape_string($_GET['sSearch_'.$i])."%' ";
}
}
$sQuery = "
SELECT SQL_CALC_FOUND_ROWS ".str_replace(" , ", " ", implode(", ", $aColumns))."
FROM $sTable
$sWhere
$sOrder
$sLimit
";
$rResult = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
/* Data set length after filtering */
$sQuery = "
SELECT FOUND_ROWS()
";
$rResultFilterTotal = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
$aResultFilterTotal = mysql_fetch_array($rResultFilterTotal);
$iFilteredTotal = $aResultFilterTotal[0];
/* Total data set length */
$sQuery = "
SELECT COUNT(".$sIndexColumn.")
FROM $sTable
";
$rResultTotal = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
$aResultTotal = mysql_fetch_array($rResultTotal);
$iTotal = $aResultTotal[0];
$output = array(
"sEcho" => intval($_GET['sEcho']),
"iTotalRecords" => $iTotal,
"iTotalDisplayRecords" => $iFilteredTotal,
"aaData" => array()
);
while ( $aRow = mysql_fetch_array( $rResult ) )
{
$row = array();
for ( $i=0 ; $i<count($aColumns) ; $i++ )
{
if ( $aColumns[$i] == "version" )
{
/* Special output formatting for 'version' column */
$row[] = ($aRow[ $aColumns[$i] ]=="0") ? '-' : $aRow[ $aColumns[$i] ];
}
else if ( $aColumns[$i] != ' ' )
{
/* General output */
$row[] = $aRow[ $aColumns[$i] ];
}
}
$output['aaData'][] = $row;
}
echo json_encode( $output );
?>
The html you're setting is being set on the client side, not on the server side, meaning that the php code will not be evaluated.
I guess what you can do is either put the already-evaluated username in a hidden tag and get that using jquery or expose it to the javascript on the page within script tags.
EDIT: So is the userID or the username in the json as well? If not, you could probably put it there. I'm still not so sure what the situation is. But if you're currently passing the userID in the json and actually want the username as bp_core_get_username would return it, why not just put the already retrieved (with bp_core_get_username) username into the json as well?
In other words, in your php code, figure out what the username is based on the userid with bp_core_get_username and then pass that into the json. That is, if I'm understanding the situation correctly.

Categories