简体   繁体   中英

Javascript Variable to PHP Session Variable and then call it via Ajax for multiple use

I am trying to server device specific layout and also content based on the browser viewport. I have a heavey site and I am not using Media Queries for some specific reasons primarily page load speeds. I need to accomplish this task in this manner only.

OK the situation is like this.....

I have 2 files index.php and viewport.php both residing in a folder http://localhost/test/

To get the browser viewport and convert the values to PHP variable, I am using the following script:

<?php
if (isset($_GET['width'])) {
  $layoutType = $_GET['width'];

      if ( $layoutType >= 240 && $layoutType <= 600 ) {
        $layoutType = 'mobile';
      } else if ($layoutType >= 601 && $layoutType <= 900 ) {
          $layoutType = 'tablet';
      } else {
         $layoutType = 'desktop';
      }
} else {
  echo "<script language='javascript'>\n";
  echo "  location.href=\"${_SERVER['SCRIPT_NAME']}?${_SERVER['QUERY_STRING']}"
            . "&width=\" + document.documentElement.clientWidth;\n";
  echo "</script>\n";
  exit();
}
?>

My questions:

Q1. How can I store $layoutType as a Session Variable so that I can use it multiple times? What would be the correct syntax for it?

Q2. How can I run the file viewport.php from index.php and get only the $layoutType and no other data. This is because by using the <?php require_once ?> method I am getting my URL like this: http://localhost/test/index.php?&width=1600 . I want the URL to display like http://localhost/test/ only. What will be the correct syntax I need to use in my index.php file?

Q3. Skipping the Ajax part is there a way to get rid of index.php?&width=1600 from the URL? I tried via .htaccess but it gives me the error saying "The page is not redirecting properly"

Please note: I do not intend to use and JavaScript Libraries like jQuery and MooTools as this is the only JavaScript function in my entire website and it wont make sense to load an entire library for it.

Firstly, PHP happens server side, so once the page loads the only way to use PHP again (without loading a page) is to make an ajax call, presumably to another php page that performs a certain function and returns a value.

If you want to store a value as a session variable so that it can be used continuously, you can do the following:

  1. when they first land on your site have php check for the existence of a session and if it does not exist, call a Javascript function to get the layoutWidth and make an ajax call to a php page that will store it as a session variable and then reload the page and include the correct layout file.

I would probably not use this method and actually look at ways to do this with JavaScript/JQuery instead. But this is how you have asked to do it.

For your example, I have not used JQuery at all, but I would as the include is only about 19kb or so and it makes life SO much easier.

Example:

index.php

<?php
   session_start();
?>
<!DOCTYPE html>
<html>
   <head>
      <title></title>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <?php 
         if (empty($_SESSION['layoutWidth'])) {
            echo '<script type="text/javascript"> var session=false; var layoutWidth;</script>';
         } else {
            echo '<script type="text/javascript"> var session=true; var layoutWidth=' . $_SESSION['layoutWidth'] . ';</script>';
         }
      ?>
      <script type="text/javascript" src="js/viewport.js"></script>
   </head>
   <body>
         <?php

            if (!empty($_SESSION['layoutWidth'])) {
               $layoutWidth = $_SESSION['layoutWidth'];
               if ( $layoutWidth >= 240 && $layoutWidth <= 900 ) {
                  include('layout1.php');
               } else if ($layoutWidth > 900 && $layoutWidth <= 1200 ) {
                  include('layout2.php');
               } else {
                  include('layout3.php');
               }
            }
         ?>
   </body>
</html>

js/viewport.js

// JavaScript Document

window.onload = function() {
    // if there is no session (session = false)
    if (!session) {
        // call function to get the screen size
        getScreenWidth();

        // make ajax call to php page to set the session variable
        setSession();
    }
}

function getScreenWidth() {
    layoutWidth = screen.width;
}

function setSession() {
    var xmlhttp;
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        // Reload the page
        window.location.reload();
        }
      }
    xmlhttp.open("POST","set_session.php?layoutWidth=" + layoutWidth,true);
    xmlhttp.send();
}

your php file to set the session the parameter is passed from your ajax call:

set_session.php

<?php
    session_start();
    // you can check if it is already set if you like otherwise:
    $_SESSION['layoutWidth'] = $_REQUEST['layoutWidth'];
?>

layout1.php

<?php
   echo '<div>This is layout1.php</div>';
   echo '<div>Your screen width is: ' . $_SESSION['layoutWidth'] . '</div>';
?>

layout2.php

<?php
  echo '<div>This is layout2.php</div>';
  echo '<div>Your screen width is: ' . $_SESSION['layoutWidth'] . '</div>';
?>

layout3.php

<?php
   echo '<div>This is layout3.php</div>';
   echo '<div>Your screen width is: ' . $_SESSION['layoutWidth'] . '</div>';
?>

This method means you dont have to pass parameters around in your URL. it will all be hidden.

Q1) $_SESSION['layoutType']=$layoutType;

Q2&Q3 ) I think you're making it too complex for yourself. Best way to achive what you want with restrictions that you have is to combine the power of cookie and session, you'll have a faster and neater code. So what you can do is check if the session layoutType is set, if not, inject a javascript code that'll get the layoutType for you and puts it in a cookie, and next time you include viewport.php in aa page, it'll check to see if the cookie is set and will transfer it to session for future use, so you can change viewport.php to this :

<?php
  if(isset($_SESSION['layoutType'])){
    //write the code for when session is set here
  }elseif(isset($_COOKIE["layoutType "])){
    $_SESSION['layoutType']=$_COOKIE["layoutType "];
  }else{
      $script = "<script language='javascript'>function SetCookie(cookieName,cookieValue) { var today = new Date(), expire = new Date(), nDays=1;expire.setTime(today.getTime() + 3600000*24*nDays);document.cookie = cookieName+'='+escape(cookieValue)+ ';expires='+expire.toGMTString();SetCookie('layoutType',document.documentElement.clientWidth}";
      echo $script;
  }
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM