How to create a div by default invisible and then show it it using ajax

I have a  a file with 3 divs:
ribbon (Must be always) visible
status-block (Only visible if the subscriber is logged in)
toolbar-block (Only visible if the subscriber is logged in)

I have created the file below which works in a way near that, it creates the 3 divs, check if the subscribers is logged in, if not it will hides, the only problem it looks ugly in the loading of the page, I wan that to be be invisible in the begining  and then display, how can I do so?

<div class="ribbon" id="ribbon">
<strong class="ribbon-content" id="ribbon-content"><img src="../images/logo.gif" alt="mysite" width="150" height="75"></strong>
</div>
<div  id="status-block">
   <label id="logged-username">Username:</label>
   <span id="logged-username-value" class="username"  >
   <br>
   <label id="logged-userIP">Client IP:</label>
   <span id="logged-userIP-value" class="userIP"  >
   <br>
   <label id="logged-priviliges">Role:</label>
   <span id="logged-priviliges-value" class="priviliges"  >
   <br>
   <label id="logged-sesssionDate">Logged On:</label>
   <span id="logged-sesssionDate-value" class="sesssionDate"  >
   <br>
   <label id="logged-sesssionTime">Logged At:</label>
   <span id="-logged-sesssionTime-value" class="sesssionTime"  >
   <br>
</div>
<div id="toolbar-block">
<div id="header-toolbar" class="ui-widget-header ui-corner-all">
<button id="logout">Logout</button>
<button id="settings">Settings</button>
</div>
  <ul id="toolbar-menu" >
    <li><a href="#">Open...</a></li>
    <li><a href="#">Save</a></li>
    <li><a href="#">Delete</a></li>
  </ul>
</div>

                <script>
                 $(function() {
                        var $logout = $("#logout").button({ text: false, icons: { primary: "ui-icon-key" } });
                        var $settings = $("#settings").button({ text: false, icons: { primary: "ui-icon-gear", secondary: "ui-icon-triangle-1-s" } });
                        var $menu = $("#settings").parent().next().show();

                $(document).click(function() {
                        $menu.hide();
                $settings.removeClass("active");
                });
                $logout.click(function() {
                                      $.ajax({
                                              url: 'logout.php',
                                              type: 'POST',
                                              data: {},
                                              success: function(response){
                                               alert (response);
                                               $("#header").load("header.php");
                                               $("#menu").load("menu.php");
                                               $("#main").load("login.php");
                                      }
                                      });

                        });
                $settings.click(function(evt) {
                        evt.stopImmediatePropagation();
                        $(this).toggleClass("active")
                        $menu.css("display", $(this).hasClass("active")?"block":"none");
                        $menu.position({ my: "left top", at: "left bottom", of: this });
                        });

                $settings.parent().buttonset().next().hide().menu();

                $menu.hover(function() {
                $(this).addClass("overme");
                }, function() {
                        if($(this).hasClass("overme")) {
                                $(this).hide();
                                $(this).removeClass("overme");
                                $settings.removeClass("active");
                                }
                        });

                $menu.click(function(evt) {
                        alert($(evt.target).text());
                        });
                });
                $.post("check_session.php", {}, function(response){
                    if(response=="true"){
                     var username= <?php echo json_encode($_SESSION['username'], JSON_HEX_TAG); ?>;
                     var userIP= <?php echo json_encode($_SESSION['userIP'], JSON_HEX_TAG); ?>;
                     var priviliges= <?php echo json_encode($_SESSION['priviliges'], JSON_HEX_TAG); ?>;
                     var sesssionDate= <?php echo json_encode($_SESSION['sessionDate'], JSON_HEX_TAG); ?>;
                     var sesssionTime= <?php echo json_encode($_SESSION['sessionTime'], JSON_HEX_TAG); ?>;
                      $("#logged-username-value").html(username);
                      $("#logged-userIP-value").html(userIP);
                      $("#logged-priviliges-value").html(priviliges);
                      $("#logged-sesssionDate-value").html(sesssionDate);
                      $("#logged-sesssionTime-value").html(sesssionTime);
                      $("#status-block").show('show');
                      $("#toolbar-block").show('show');
                     } else {
                      $("#status-block").hide();
                      $("#toolbar-block").hide();
                          }
                });
                </script>

Open in new window

Ashraf HassaneinAsked:
Who is Participating?
 
Ray PaseurConnect With a Mentor Commented:
See if this makes sense.  It's just a mockup, but it shows how to fire an event handler that allows display of an element that was invisible at page-load time.
http://www.laprbass.com/RAY_temp_ashraf_hassanein.php

<?php // RAY_temp_ashraf_hassanein.php
error_reporting(E_ALL);

// CREATE VARIABLES FOR OUR HTML
$dat = date('r');
$xyz = "Hello World.  It is $dat";

// CREATE OUR WEB PAGE IN HTML5 FORMAT
$htm = <<<HTML5
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
<meta charset="utf-8" />
<meta name="robots" content="noindex, nofollow" />

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>

<script>
$(document).ready(function() {
    $( "#clickme" ).click(function() {
        $( "#secrets" ).show( "slow", function() {
            alert( "Animation complete." );
        });
    });
});
</script>

<style type="text/css">
#secrets {
    display:none;
}
</style>

<title>HTML5 Page in UTF-8 Encoding</title>
</head>
<body>

<div id="clickme">
CLICK HERE TO SIMULATE A LOGIN AND ALLOW DISPLAY OF SECRET INFORMATION
</div>

<p id="secrets">HERE IS THE SECRET INFORMATION: $xyz</p>
</body>
</html>
HTML5;

// RENDER THE WEB PAGE
echo $htm;

Open in new window

0
 
Ray PaseurCommented:
Added jQuery and JavaScript Zones.
0
 
Ray PaseurCommented:
Check into "document.ready" for jQuery.  It will cause the functions to not be run until, well, the document is ready.  Make your initial setting for the "iffy" divs be hidden, then use "show" if your client is authenticated.
http://api.jquery.com/ready/
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
Ashraf HassaneinAuthor Commented:
I have changed the script part to:

                <script>
                 $( document ).ready(function() {
                        var $logout = $("#logout").button({ text: false, icons: { primary: "ui-icon-key" } });
                        var $settings = $("#settings").button({ text: false, icons: { primary: "ui-icon-gear", secondary: "ui-icon-triangle-1-s" } });
                        var $menu = $("#settings").parent().next().show();

                $(document).click(function() {
                        $menu.hide();
                $settings.removeClass("active");
                });
                $logout.click(function() {
                                      $.ajax({
                                              url: 'logout.php',
                                              type: 'POST',
                                              data: {},
                                              success: function(response){
                                               alert (response);
                                               $("#header").load("header.php");
                                               $("#menu").load("menu.php");
                                               $("#main").load("login.php");
                                      }
                                      });

                        });
                $settings.click(function(evt) {
                        evt.stopImmediatePropagation();
                        $(this).toggleClass("active")
                        $menu.css("display", $(this).hasClass("active")?"block":"none");
                        $menu.position({ my: "left top", at: "left bottom", of: this });
                        });

                $settings.parent().buttonset().next().hide().menu();

                $menu.hover(function() {
                $(this).addClass("overme");
                }, function() {
                        if($(this).hasClass("overme")) {
                                $(this).hide();
                                $(this).removeClass("overme");
                                $settings.removeClass("active");
                                }
                        });

                $menu.click(function(evt) {
                        alert($(evt.target).text());
                        });
                });
                $.post("check_session.php", {}, function(response){
                    if(response=="true"){
                     var username= <?php echo json_encode($_SESSION['username'], JSON_HEX_TAG); ?>;
                     var userIP= <?php echo json_encode($_SESSION['userIP'], JSON_HEX_TAG); ?>;
                     var priviliges= <?php echo json_encode($_SESSION['priviliges'], JSON_HEX_TAG); ?>;
                     var sesssionDate= <?php echo json_encode($_SESSION['sessionDate'], JSON_HEX_TAG); ?>;
                     var sesssionTime= <?php echo json_encode($_SESSION['sessionTime'], JSON_HEX_TAG); ?>;
                      $("#logged-username-value").html(username);
                      $("#logged-userIP-value").html(userIP);
                      $("#logged-priviliges-value").html(priviliges);
                      $("#logged-sesssionDate-value").html(sesssionDate);
                      $("#logged-sesssionTime-value").html(sesssionTime);
                      $("#status-block").show('show');
                      $("#toolbar-block").show('show');
                     } else {
                      $("#status-block").hide();
                      $("#toolbar-block").hide();
                          }
                });
                </script>

Open in new window


And I have tried
<div  id="status-block" style="display: none;">
<div  id="toolbar-block" style="display: none;">

Open in new window


But that was no hiding the display

and

<div  id="status-block" style="display: none; visibility: hidden;">
<div  id="toolbar-block" style="display: none; visibility: hidden;">

Open in new window


But that was not showing it at all


One further point this file is actually called with a div container of the main page, so I am not sure if the document ready will work per div idependently or for the entire file?
0
 
Ashraf HassaneinAuthor Commented:
In you example above I can see you that you created the paragraph already with no hide,
 but also you have created the event to show the paragraph in the same the file as the link to show it, where in my case they are physically in 2 different, and this the script section is the in the local file and not the main file of the container, do you advise to change that?
0
 
Ray PaseurCommented:
Hmm..  Maybe a few things to consider (not sure, but worth asking).

Hyphens in data element names, such as markup tags, can be confusing.  Consider that status-block could be interpreted as a tag name or as a computation, eg: var status minus var block.  For this reason I try to avoid using hyphens in names.  (It's a real nasty thing to have hyphenated tags in XML or JSON).  I am sure you can quote these things in some way that will lead to correct interpretation, but I'm not smart enough to remember that all the time!

Selectors with the # in the front, like #secrets in this example are for unique page elements.   Since they are unique, they can be selected no matter where in the page they reside, including inside of other <div> or similar HTML constructs.

<head>
<meta charset="utf-8" />
<meta name="robots" content="noindex, nofollow" />

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>

<script>
$(document).ready(function() {
    $( "#clickme" ).click(function() {
        $( "#secrets" ).fadeIn( "slow" );
    });
});
</script>

<style type="text/css">
#secrets {
    display:none;
}
</style>

<title>HTML5 Page in UTF-8 Encoding</title>
</head>
<body>

<div id="clickme">
CLICK HERE TO SIMULATE A LOGIN AND ALLOW DISPLAY OF SECRET INFORMATION
</div>

<div id="mainpage">
<p id="secrets">HERE IS THE SECRET INFORMATION: $xyz</p>
</div>
</body>
</html>
HTML5;

// RENDER THE WEB PAGE
echo $htm;

Open in new window

If you want to read a really good book on jQuery, ignore the hokey title and just buy this one.  It's excellent and comes with a money-back guarantee.
http://www.sitepoint.com/store/jquery-novice-to-ninja-new-kicks-and-tricks/
0
 
Ashraf HassaneinAuthor Commented:
I can change the name, but do advise to put the script managing the hide disappear  and display in the main container page as $(document).ready(function() will be called only one in the main page or it can be called per div?
0
 
Ray PaseurCommented:
Some things to note about the script above.

Line 16 identifies the #secrets id selector, and styles it initially with display:none; to make it invisible on page load.

Line 8-12 is the jQuery to fire an event handler for the click on #clickme.  It will select the #secrets element and apply the fadeIn() function causing it to become visible.

Even though this demonstrates the ability to hide a data element and show it after an event occurs, you probably do not want to do this exact thing if you have sensitive data.  The data is present in the document, but hidden before the #clickme even, so it can be discovered by using the browser "view source."  Instead, you would probably want to have a hidden div that gets loaded via an AJAX call.  Then after the AJAX call, you can reveal the contents of the div.  This article shows the most basic example.
http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Jquery/A_10712-The-Hello-World-Exercise-with-jQuery-and-PHP.html
0
 
Ray PaseurCommented:
Not quite sure I understand the question at this point.  Here is my "flyover" explanation of the process.

1. Use PHP or some combination of PHP and HTML to create the web page document.
2. Make any "secret" div be styled "display:none" and empty of information
3. On an action such as a click of the login button, transmit the credentials to the back-end script that will validate the credentials
4. Put the response from the back-end script into the empty secret div and reveal it with jQuery .show() or .fadein()
5. The page will now show a "welcome" message or "login failed" depending on the response from the back-end validation script.

Does that make sense?
0
 
Ashraf HassaneinAuthor Commented:
Here is the main site page as you can see there is not script, but the script is called mainly in the header.php.

<?php
session_start();
?>
<HTML>
<HEAD>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title>HASSANS</title>
        <link rel="SHORTCUT ICON" type="image/x-icon" href="../images/hassans-icon-xl.ico">
        <link rel="stylesheet" type="text/css" href="css/main.css">
        <link rel="stylesheet" type="text/css" href="css/jquery.ui.all.css">
        <script type="text/javascript" src="js/jquery-1.10.1.min.js"></script>
        <script type="text/javascript" src="js/jquery-ui-1.10.3.custom.min.js"></script>
</HEAD>
<BODY>
 <div class="header-frame" name="header" id="header">
   <?php include("header.php"); ?>
</div>
<div id="bottom">
 <div class="menu-frame" name="menu" id="menu">
   <?php include("menu.php"); ?>
 </div>
 <div class="main-frame" name="main" id="main">
   <?php include("login.php"); ?>
 </div>
 </div>
</BODY>
</HTML>

Open in new window

so will the dcoument ready funtion be useful if it is called from the local  div file rather than the main file?
0
 
leakim971Connect With a Mentor PluritechnicianCommented:
<div  id="status-block" style="display: none; visibility: hidden;">

Open in new window


But that was not showing it at all

Use only : display: none;
and use jQuery("what_to_show").show() to display
or use jQuery("what_to_show").css("display", "block")

Or Use only : visibility: hidden;
and use jQuery("what_to_show").css("visibility", "visible")

the difference is visibility don't "remove" the object from the page, the object is only not visible, it fill the place with its width and height
unlike display "remove" the object from the page

when I say "remove" I want to say it's still present in the DOM (document) but not visible
0
 
Ray PaseurCommented:
so will the document ready function be useful if it is called from the local  div file rather than the main file?
The answer to that will be dependent on the HTML that is generated by the PHP scripts.  My organizational strategy would be to put the JavaScript somewhere that it will always be present in the document.  Hiding it inside an included script might make sense, but I would probably put that include() statement in the header of the HTML document.
0
 
Ashraf HassaneinAuthor Commented:
Thank you so much Ray thank you so much leakim971 now the problem is clear to be and I solved :-)
0
 
Ashraf HassaneinAuthor Commented:
Thanks for the expert, I was not able really to identify the best answer because both of them helped me alot
0
 
Ray PaseurCommented:
Great!

Going forward you might consider using the CDN for jquery.  It will lighten the load on your server and it will always be up-to-date.

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
0
 
leakim971PluritechnicianCommented:
If you still want to use javascript to show/hide the div, you may update your PHP script check_session.php to return user infos too,
so response look like :
{
   connected:true,
   username:"leakim971",
   userIP:"127.0.0.1",
   priviliges:"root;of;course",
   sessionDate:"12/31/1969",
   sessionTime:"20:00:00"
}

Open in new window


Test pages :
- Connected : http://jsfiddle.net/H699A/
- Not connected : http://jsfiddle.net/H699A/1/

$.post("check_session.php", {}, function(response){
	$("#logged-username-value").html(response.username);
	$("#logged-userIP-value").html(response.userIP);
	$("#logged-priviliges-value").html(response.priviliges);
	$("#logged-sesssionDate-value").html(response.sesssionDate);
	$("#logged-sesssionTime-value").html(response.sesssionTime);
	$("#status-block").css("display", response.connected?"block":"none");
	$("#toolbar-block").css("display", response.connected?"block":"none");
});

Open in new window

0
All Courses

From novice to tech pro — start learning today.