Tutorial :Making a Link Appear if a Condition is Met



Question:

The PHP code below echoes a link if the "loginid" of the logged-in user is on a list determined by getEditorList();. It works fairly well, but I think it might work better if I were to do it with Javascript instead.

How could I accomplish the same thing with Javascript?

Thanks in advance,

John

$editors = getEditorsList();              foreach($editors as $editor)              {              $editorids[] = $editor['loginid'];              }                if(in_array($_SESSION['loginid'], $editorids))              {              echo "<div class='footervote'><a href='http://www...com/.../footervote.php'>Vote</a></div>";              }   

Login function:

<?php  if (!isLoggedIn())  {        if (isset($_POST['cmdlogin']))      {            if (checkLogin($_POST['username'], $_POST['password']))          {              show_userbox();              } else          {              echo "Incorrect Login information !";              show_loginform();          }      } else      {            show_loginform();      }    } else  {        show_userbox();    }        ?>  


Solution:1

So actually, your problem is "After a user logs in, he often still gets the non-logged in version of the pages", and you propose the "Make the link appear in Javascript" as a solution. Then you ask how to do that :)

RoToRa already pointed out that the cause of your problem probably has to do with the browser cashing the pages, and not requesting a new page after the user has logged in, but showing the old page from cache. There are several solutions for this, even with Javascript.

To avoid caching:

  • Add a 'Pragma: No-Cache' header to your page.
  • Add a 'Expires: -1' header to your page.
  • Use the Cache-Control HTTP headers from HTTP 1.1

Check the PHP header function for more information how to do that in PHP, or read your webservers documentation.

Another possible solution is to have the page serve as static, and then use AJAX to check if the user is logged-in, and if so, load the custom content for that user. Typically you'll create an extra php-script to check if the user is logged in, and have the AJAX call this script. This is quite easy to do using a decent Javascript library like jQuery, but you can do it without libraries should you really need to do so.

Checkout PHP JSON, jQuery AJAX for more info about those solutions.

A last often (ab)used solution is to have a query string for your page - browsers will see the query string is different, and won't cache the page.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »