Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how do I auto-refresh a hidden JS popup so the page does not need to re-load to display the updates?

Status
Not open for further replies.

zoldos

Technical User
Nov 5, 2008
90
0
0
US
This is the complete bit of code from my header.tpl. Currently, it will only display the hidden JS pop up if there are new site updates AND you refresh the page. I'd like it to auto-refresh say every 30 or 45 seconds, perhaps sooner for a more "real time" feel to the site.

I'm still a JS noob, so any help would be most appreciated! :)

Code:
<div style='display: none;' id='newupdates_popup'>
    <div style='margin-top: 10px;align:right;'>
      {assign var="notifyscount" value=$notifys[0]|@count}
      {lang_sprintf id=1199 1="<span id='notifyscount'>`$notifyscount`</span>"}
    </div>
    {section name=notify_loop loop=$notifys[0]}
      <div style='font-weight: bold; padding-top: 5px;' id='notify_{$notifys[0][notify_loop].notifytype_id}_{$notifys[0][notify_loop].notify_grouped}'>
        <a title='Remove Notification' style='color:#000000;' href='javascript:void(0);' onClick="parent.deleteNotify('{$notifys[0][notify_loop].notifytype_id}', '{$notifys[0][notify_loop].notify_grouped}');">X</a> <img src='./images/icons/{$notifys[0][notify_loop].notify_icon}' border='0' style='border: none; margin: 0px 5px 0px 5px; display: inline; vertical-align: middle;' class='icon'><a href="{$notifys[0][notify_loop].notify_url}">{lang_sprintf id=$notifys[0][notify_loop].notify_desc 1=$notifys[0][notify_loop].notify_total 2=$notifys[0][notify_loop].notify_text[0]}</a></div>
    {/section}
    </div>
  </div>

{literal}
<script type='text/javascript'>
<!--

var se_show_newupdates = new Hash.Cookie('se_show_newupdates', {duration: 3600});

{/literal}{if $notifys[1] != 0}{literal}
  window.addEvent('domready', function() {
    if(se_show_newupdates.get('total') < {/literal}{$notifys[1]}{literal}) {
      se_show_newupdates.set('total', '0');
      $('newupdates').style.display='block';
    }
  });

{/literal}{/if}{literal}
var notify_count = {/literal}{$notifys[1]}{literal};
function deleteNotify(notifytype_id, notify_grouped) {
  $('ajaxframe').src = 'misc_js.php?task=notify_delete&notifytype_id='+notifytype_id+'&notify_grouped='+notify_grouped;
}
function deleteNotifyConfirm(notifytype_id, notify_grouped) {
  $("TB_window").getElements('div[id=notify_'+notifytype_id+'_'+notify_grouped+']').each(function(el) { if(el.id == 'notify_'+notifytype_id+'_'+notify_grouped) { el.style.display = 'none'; notify_count--; }});
  $('newupdates_popup').getElements('div[id=notify_'+notifytype_id+'_'+notify_grouped+']').each(function(el) { if(el.id == 'notify_'+notifytype_id+'_'+notify_grouped) { el.style.display = 'none'; }});
  $('notify_total').innerHTML = notify_count;
  $("TB_window").getElements('span[id=notifyscount]').each(function(el) { if(el.id == 'notifyscount') { el.innerHTML = notify_count; }});
  if(notify_count == 0) {
    TB_remove();
    $('newupdates').style.display = 'none';
  }
}
function hideNewupdates() {
  $('newupdates').fade('out');
  se_show_newupdates.set('total', '{/literal}{$notifys[1]}{literal}');
}
function SwapOut(id1) {
  $(id1).src = Rollarrow1.src;
  return true;
}
function SwapBack(id1) {
  $(id1).src = Rollarrow0.src;
  return true;
}
//-->
</script>
{/literal}
{/if}
 
take a look at window.setInterval
and $.ajax in the jQuery framework.
 
Can I do it with just window.setInterval? I always have problems with jQuery despite the fact that parts of my site use it. ?? lol
 
Okay I added this just after the last "}":
Code:
setInterval("window.addEvent('domready', function()",15000);
But it doesn't seem to work. I'm not exactly sure what part of the main JS fires to show the updates (if any) or even if my syntax of setInterval is correct. :(
 
the window.addEvent adds an event listener. you can do that every few seconds if you want, but it seems pointless as once will do.

you can avoid ajax, but then your page MUST refresh every interval. this is disastrous if there are any user-interactive elements on the page, and often it causes the page to jump on refresh - which is really annoying. consider instead having the refreshing part in an iframe, and refreshing the iframe only.

what part of the main JS fires to show the updates
none of the js you have posted above causes a refresh or pulls in external content.

the only dynamic aspect is the following pseudocode:

1. if the total number of updates stored in the cookie is less than the total number of updates reported by the server on refresh
2. THEN show the updates div
3. ELSE hide the updates div

i.e. the information in the updates div is either static (refreshed only on page load by the server) or is dealt with in sections that you have not provided.

if you really must refresh the whole page each interval then you can use the setInterval if javascript is supported, although since it will only ever fire once, setTimeout is better.

Code:
$(document).ready(function(){
var interval = 60000; //number of milliseconds
setTimeout( document.location.reload( true ), interval);
});
or 
window.onLoad(function(){
var interval = 60000; //number of milliseconds
setTimeout( document.location.reload( true ), interval);
});

but you can also use a non-javascript solution such as meta-refresh:
none of these are good practice. as above: use ajax or an iframe. and really think hard about abandoning smarty: the learning and using overhead is significant for limited benefit compared to other content management systems or better still, coding this yourself.
 
I'd rather just refresh the notify section div. How do I use an Iframe for that? Here is the HTML portion of the code:

Code:
  <div style='display: none;' id='newupdates_popup'>
    <div style='margin-top: 10px;align:right;'>
      {assign var="notifyscount" value=$notifys[0]|@count}
      {lang_sprintf id=1199 1="<span id='notifyscount'>`$notifyscount`</span>"}
    </div>
    {section name=notify_loop loop=$notifys[0]}
      <div style='font-weight: bold; padding-top: 5px;' id='notify_{$notifys[0][notify_loop].notifytype_id}_{$notifys[0][notify_loop].notify_grouped}'>
        <a title='Remove Notification' style='color:#000000;' href='javascript:void(0);' onClick="parent.deleteNotify('{$notifys[0][notify_loop].notifytype_id}', '{$notifys[0][notify_loop].notify_grouped}');">X</a> <img src='./images/icons/{$notifys[0][notify_loop].notify_icon}' border='0' style='border: none; margin: 0px 5px 0px 5px; display: inline; vertical-align: middle;' class='icon'><a href="{$notifys[0][notify_loop].notify_url}">{lang_sprintf id=$notifys[0][notify_loop].notify_desc 1=$notifys[0][notify_loop].notify_total 2=$notifys[0][notify_loop].notify_text[0]}</a></div>
    {/section}
    </div>
  </div>
 
I use a pre-written script that is fully integrated with Smarty and I do various source code mods for better functionality.
 
zoldos - i could not tell you how to do that without fully grokking your smarty code and how it is set up. I suggest talking with whomever crafted your templating system.

you would need to change the front end (straight forward); and change the back-end (no idea how to do that using smarty. If you used straight php it could be done in a few minutes.).
 
Thanks! So there is no other (simple) way you know to refresh just that particular part of the code?
 
So there is no other (simple) way you know to refresh just that particular part of the code?
there is, yes. but without knowing how the back-end of the site is configured and managed and structured, i would have no idea how to point you in the right direction to get going.

If you can access the structure, database and the updates etc without resorting to smarty, then I can help. Otherwise I fear you need to talk to the template developer.

it would also help to see the rendered html/javascript WITHOUT the smarty tags everywhere. so the view-source of the web-page generated by this template. that will help with half the problem.
 
Okay, gotcha. I did post this question on a Smarty forum and a few other places. I can post the PHP source of the template in question for you to check out, but it's full of Smarty tags. Let me know, and thanks a bunch for your help this far!
 
It would take me too long to relearn smarty. and it's not the smarty page that loads this page that will be an issue. you will need to create a new receiving script that handles ajax calls. so much easier to do in non-smarty php.
 
Okay, I have some alternative code, that does the same thing, but uses almost pure HTML. Tell me what you think of it, and if it's easier to work with:

Code:
{if $notifys[1] != 0}
<table cellpadding='0' cellspacing='0' align='center' width='50%'>
  <tr><td class='header'><center>Updates & Notifications</center></td></tr>
  <tr>
  <td class='home_box'>
    <div>
    <center>
         {section name=notify_loop loop=$notifys[0]}
      <div style='font-weight: bold; padding-top: 5px;' id='notify_{$notifys[0][notify_loop].notifytype_id}_{$notifys[0][notify_loop].notify_grouped}'>
        <img src='./images/icons/{$notifys[0][notify_loop].notify_icon}' border='0' style='border: none; margin: 0px 5px 0px 5px; display: inline; vertical-align: middle;' class='icon'><a href="{$notifys[0][notify_loop].notify_url}">{lang_sprintf id=$notifys[0][notify_loop].notify_desc 1=$notifys[0][notify_loop].notify_total 2=$notifys[0][notify_loop].notify_text[0]}</a></div>
    {/section}
    </center>
    </div>
  </td>
  </tr>
  </table>
<br>
{/if}

:)
 
nope. we need to know what is going on inside smarty in that loop.
or we need to know how to access the updates from outside of smarty. which would be a much better solution.


what are these updates? where do they come from? how are they stored? where are they stored?
 
Okay, well I appreciate the help anyway, looks like this one is beyond my ability, and without providing you my entire source code, it doesn't seem like it can be done...

For one more last ditch effort, here is the source PHP for header.tpl:

Code:
<?php

// PREVENT MULTIPLE INCLUSION
if( defined('SE_HEADER') ) return;

// SET ERROR REPORTING
error_reporting(E_ALL ^ E_WARNING ^ E_NOTICE);
ini_set('display_errors', TRUE);

// ATTEMPT TO OVERLOAD STRING FUNCTIONS
if( @extension_loaded('mbstring') ) @ini_set('mbstring.func_overload', 2);

// CHECK FOR PAGE VARIABLE
if( !isset($page) ) $page = "";

// DEFINE SE CONSTANTS
define('SE_DEBUG', FALSE);
define('SE_PAGE', TRUE);
define('SE_ROOT', realpath(dirname(__FILE__)));
define('SE_HEADER', TRUE);

// SET INCLUDE PATH TO ROOT OF SE
set_include_path(get_include_path() . PATH_SEPARATOR . realpath("./"));

// BENCHMARK
include "include/class_benchmark.php";
$_benchmark = SEBenchmark::getInstance('default');
SE_DEBUG ? $_benchmark->start('total') : NULL;
SE_DEBUG ? $_benchmark->start('include') : NULL;



// INITIATE SMARTY
include "include/class_smarty.php";
$smarty =& SESmarty::getInstance();
//$smarty->debugging = TRUE;

// INCLUDE DATABASE INFORMATION
include "include/database_config.php";

// INCLUDE CLASS/FUNCTION FILES
include "include/functions_file.php";
include "include/cache/cache.php";
include "include/cache/storage.php";
include "include/session/session.php";
include "include/session/storage.php";

include "include/class_core.php";

include "include/class_admin.php";
include "include/class_database.php";
include "include/class_datetime.php";
include "include/class_comment.php";
include "include/class_field.php";
include "include/class_hook.php";
include "include/class_language.php";
include "include/class_notify.php";
include "include/class_upload.php";
include "include/class_user.php";
include "include/class_url.php";
include "include/class_misc.php";
include "include/class_ads.php";
include "include/class_actions.php";
include "include/functions_general.php";
include "include/functions_email.php";
include "include/functions_stats.php";

// JS API MOD JSON FUNCTIONS
include "include/class_javascript.php";
if(!function_exists('json_encode'))
{
  include_once "include/xmlrpc/xmlrpc.inc";
  include_once "include/xmlrpc/xmlrpcs.inc";
  include_once "include/xmlrpc/xmlrpc_wrappers.inc";
  include_once "include/jsonrpc/jsonrpc.inc";
  include_once "include/jsonrpc/jsonrpcs.inc";
  include_once "include/jsonrpc/json_extension_api.inc";
}


SE_DEBUG ? $_benchmark->end('include') : NULL;
SE_DEBUG ? $_benchmark->start('initialization') : NULL;



// INITIATE DATABASE CONNECTION
$database =& SEDatabase::getInstance();
// Use this line if you changed the way database connection is loaded
//$database = new SEDatabase($database_host, $database_username, $database_password, $database_name);

// SET DATABASE CONSTANTS
$database->database_query("SET @SE_PRIVACY_SELF = 1, @SE_PRIVACY_FRIEND = 2, @SE_PRIVACY_FRIEND2 = 4, @SE_PRIVACY_SUBNET = 8, @SE_PRIVACY_REGISTERED = 16, @SE_PRIVACY_ANONYMOUS = 32");

// SET LANGUAGE CHARSET
$database->database_set_charset(SE_Language::info('charset'));

// GET SETTINGS
$setting =& SECore::getSettings();

// CREATE URL CLASS
$url = new SEUrl();

// CREATE DATETIME CLASS
$datetime = new se_datetime();

// CREATE MISC CLASS
$misc = new se_misc();

// ENSURE NO SQL INJECTIONS THROUGH POST OR GET ARRAYS
$_POST = security($_POST);
$_GET = security($_GET);
$_COOKIE = security($_COOKIE);

// CREATE SESSION OBJECT
$session_options = ( defined('SE_SESSION_RESUME') && !empty($session_id) ? array('id' => $session_id, 'security' => array()) : array() );
$session = SESession::getInstance($session_options);
if( $session->getState() == 'expired' )
{
  $session->restart();
}

// CHECK FOR PAGE OWNER
if(isset($_POST['user'])) { $user_username = $_POST['user']; } elseif(isset($_GET['user'])) { $user_username = $_GET['user']; } else { $user_username = ""; }
if(isset($_POST['user_id'])) { $user_id = $_POST['user_id']; } elseif(isset($_GET['user_id'])) { $user_id = $_GET['user_id']; } else { $user_id = ""; }
$owner = new SEUser(Array($user_id, $user_username));

// CREATE USER OBJECT AND ATTEMPT TO LOG USER IN
$user = new SEUser();
$user->user_checkCookies();

// INSTANTIATE JAVASCRIPT OBJECT
$se_javascript = new SE_Javascript();


// CREATE ADMIN OBJECT AND ATTEMPT TO LOG ADMIN IN
$admin = new se_admin();
$admin->admin_checkCookies();


// CANNOT ACCESS USER-ONLY AREA IF NOT LOGGED IN
if( !$user->user_exists && substr($page, 0, 5) == "user_" )
{
  header("Location: login.php?return_url=".$url->url_current());
  exit();
}

// SET GLOBAL TIMEZONE
$global_timezone = ( $user->user_exists ? $user->user_info['user_timezone'] : $setting['setting_timezone'] );

// PRO CHAT ROOMS - One2One CMS Chat
setcookie("prochatrooms_init", $user->user_info[user_username], 0, "/");

// SET UP LANGUAGE VARIABLES
if( !empty($_GET['lang_id']) )
{
  $lang_id = NULL;
  if( $user->user_exists && $setting['setting_lang_allow'] )
  {
    $lang_id = $user->user_info['user_language_id'] = (int)$_GET['lang_id'];
    $database->database_query("UPDATE se_users SET user_language_id='{$user->user_info['user_language_id']}' WHERE user_id='{$user->user_info['user_id']}' LIMIT 1");
  }
  
  if( !$user->user_exists && $setting['setting_lang_anonymous'] )
  {
    $lang_id = (int)$_GET['lang_id'];
  }
  
  if( $lang_id )
  {
    setcookie('se_language_anonymous', $lang_id, time()+99999999, "/");
    $_COOKIE['se_language_anonymous'] = $lang_id;
  }
}

SE_Language::select($user);

if( SE_Language::info('language_setlocale') )
{
  $multi_language = 1;
  setlocale(LC_TIME, SE_Language::info('language_setlocale'));
}

header("Content-Language: ".SE_Language::info('language_code'));


// CREATE ACTIONS CLASS
$actions = new se_actions();

// CREATE NOTIFICATION CLASS
$notify = new se_notify();

// CREATE ADS CLASS
$ads = new se_ads();

// Define SE_PAGE_AJAX in your page before the header include to not load ads or update page views
if( !defined('SE_PAGE_AJAX') && ($page=="chat_frame" || $page=="chat_ajax" || $page=="misc_js" || $page=="ad") )
  define('SE_PAGE_AJAX', TRUE);

if( !defined('SE_PAGE_AJAX') )
{
  // UPDATE STATS TABLE
  update_stats("views");
  
  // LOAD ADS
  $ads->load();
}


// CREATE GLOBAL CSS STYLES VAR (USED FOR CUSTOM USER-DEFINED PROFILE/PLUGIN STYLES)
$global_css = "";


SE_DEBUG ? $_benchmark->end('initialization') : NULL;

SE_DEBUG ? $_benchmark->start('plugins') : NULL;



// INCLUDE RELEVANT PLUGIN FILES
// AND SET PLUGIN HEADER TEMPLATES
$show_menu_user = FALSE;

$global_plugins =& SECore::getPlugins();

foreach( $global_plugins as $plugin_type=>$plugin_info )
{
  $plugin_vars = array();
  if( file_exists("header_{$plugin_info['plugin_type']}.php") )
  {
    include "header_{$plugin_info['plugin_type']}.php";
  }
  
  // Set the hooks for each of the plugin templates if not using the new hooked template includes (backwards compatibility)
  if( empty($plugin_vars['uses_tpl_hooks']) )
  {
    if( file_exists(SE_ROOT."/templates/header_{$plugin_info['plugin_type']}.tpl") )
      $smarty->assign_hook('header', "header_{$plugin_info['plugin_type']}.tpl");
    
    if( file_exists(SE_ROOT."/templates/footer_{$plugin_info['plugin_type']}.tpl") )
      $smarty->assign_hook('footer', "footer_{$plugin_info['plugin_type']}.tpl");
    
    if( !empty($plugin_vars['menu_main']) )
      $smarty->assign_hook('menu_main', $plugin_vars['menu_main']);
    
    if( !empty($plugin_vars['menu_user']) )
      $smarty->assign_hook('menu_user_apps', $plugin_vars['menu_user']);
    
    if( $page=="profile" && !empty($plugin_vars['menu_profile_side']) )
    {
      $plugin_vars['menu_profile_side']['name'] = $plugin_info['plugin_type'];
      $smarty->assign_hook('profile_side', $plugin_vars['menu_profile_side']);
    }
    
    if( $page=="profile" && !empty($plugin_vars['menu_profile_tab']) )
    {
      $plugin_vars['menu_profile_tab']['name'] = $plugin_info['plugin_type'];
      $smarty->assign_hook('profile_tab', $plugin_vars['menu_profile_tab']);
    }
    
    if( $page=="user_home" && !empty($plugin_vars['menu_userhome']) )
    {
      $plugin_vars['menu_userhome']['name'] = $plugin_info['plugin_type'];
      $smarty->assign_hook('user_home', $plugin_vars['menu_userhome']);
    }
  }
  
  // If using the new template hooks, the header should also hook the styles sheets
  
  $global_plugins[$plugin_info['plugin_type']] =& $plugin_vars;
  if( !empty($plugin_vars['menu_user']) ) $show_menu_user = TRUE;
  unset($plugin_vars);
}

$global_plugins['plugin_controls'] = array('show_menu_user' => $show_menu_user);



SE_DEBUG ? $_benchmark->end('plugins') : NULL;
SE_DEBUG ? $_benchmark->start('page') : NULL;



// CHECK TO SEE IF SITE IS ONLINE OR NOT, ADMIN NOT LOGGED IN, DISPLAY OFFLINE PAGE
if( !$setting['setting_online'] && !$admin->admin_exists )
{
  $page = "offline";
  include "footer.php";
}


// CALL HEADER HOOK
($hook = SE_Hook::exists('se_header')) ? SE_Hook::call($hook, array()) : NULL;


// CHECK IF LOGGED-IN USER IS ON OWNER'S BLOCKLIST
if( $user->user_exists && $owner->user_exists && $owner->user_blocked($user->user_info['user_id']) )
{
  // ASSIGN VARIABLES AND DISPLAY ERROR PAGE
  $page = "error";
  $smarty->assign('error_header', 639);
  $smarty->assign('error_message', 640);
  $smarty->assign('error_submit', 641);
  include "footer.php";
}


// CHECK TO SEE IF USER HAS BEEN BLOCKED BY IP
$banned_ips = explode(",", $setting['setting_banned_ips']);
if( in_array($_SERVER['REMOTE_ADDR'], $banned_ips) )
{
  // ASSIGN VARIABLES AND DISPLAY ERROR PAGE
  $page = "error";
  $smarty->assign('error_header', 639);
  $smarty->assign('error_message', 807);
  $smarty->assign('error_submit', 641);
  include "footer.php";
}


// Get online users
$online_array = online_users();

$smarty->assign_by_ref('online_users', $online_array);

// GET NEWS ITEMS
$news_array = site_news();

$smarty->assign_by_ref('news', $news_array);

?>
 
Got it working with an ingenious bit of code from a support site for the script I'm using. I tinkered with it and what do ya know!. :) Thanks for your time!!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top