Adam Caron
Adam Caron

Reputation: 401

Determine browser width with jQuery, then call one (out of two) .php files (from the same directory) to load a line of PHP

I seek a simple way to call a php file using jquery.

The ultimate outcome has to do with a Magento site I am working on: http://bouquetsco.com/flowersplants.html ^^This page

This page displays products: 3 in a row.

    <?php $this->setColumnCount(3); ?>
    <?php $this->setColumnCount(2); ?>

^^This php code manually sets the number of product columns.

By default the page displays 3 wide, which looks fine until the browser window re-sizes down to tablet width (760px or so). When the website's design is tablet size (760px or so) I would like to display only two columns of products.

To do this, it seems one must use javascript to determine the window width, then run some php code depending on the browser-window width... like

this...

    if ( browser-window-widith > 760) { get '3-column.php' }
    else { get '2-column.php' }

This is grossly over-simplified. What would this code logic look like? How would one write this functionality?

Also, one could change the initial if statement to:

    if (browser-window-width < 760) { get '2-column.php' }
    else { get '3-column.php' }

====================================

There would exist two .php files (2-column.php, & 3-column.php) Each contains:

    <?php $this->setColumnCount(2); ?>

or

    <?php $this->setColumnCount(3); ?>

The code would call one file or another depending on the browser window width, (which would be found by the javascript) and thus result in

3-column product list for displays > 760px

and

2-column product list for displays < 760px

Upvotes: 1

Views: 1111

Answers (2)

ROY Finley
ROY Finley

Reputation: 1416

I use this on the login page of my site:

if(!isset($_GET['width']))
    {
        echo '<script type="text/javascript">window.location = "' . $_SERVER['PHP_SELF'] . '?width="+screen.width+"&height="+screen.height;</script>';
    }
    else
        {
            $_SESSION['screen_width'] = $_GET['width'];
            $_SESSION['screen_height'] = $_GET['height'];
        }

Now the width and height are saved to the current session, and I can do a condition check before displaying the page division.

if($_SESSION['screen_width']>= '1400')
   {
      $this->setColumnCount(3);
   }
   else
       {
          $this->setColumnCount(2);
       }

Upvotes: 1

You can use jquery width and some ajax calls.

index.php

<html>
....
<div id="somedivport"></div>
<--! if that script is used the above div will load differently depending on the width-->
</html>

script.js

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
    //or use this$(document).width(); 
    $("#somedivport").load(width>$(window).width()?"/3-column.php":"/2-column.php");
});
</script>

Edit for reducing kloc

Upvotes: 0

Related Questions