1

I would like, when i'm loading a webpage, to add in GET the width and height of the screen, so that my page can use these var to redirect to a specific page.

I've looked for the function and it seems that I should use window.screen.width and window.screen.height

Also, I figured out I should use $.get() to send the variables.

So I came out with this script, but i assume i'm mixing JS and AJAX which I don't if it's ok or not. And most of all, I don't know how to run the function when my page is loading.

    $(document).ready(function() {
    ratio();
function ratio() {
    var Vorientation;
    if(window.screen.width>window.screen.height)
    {
       Vorientation = 1;
    }
    else
    {
       Vorientation = 2;
    }
    $.get( "index.php?orientation="+Vorientation );
    alert("ok");
 }
  });

Here is the html :

    <body>

<?php 
if(isset($_GET['orientation']))
{
echo"ok";
} 
?>

</body>
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
B.T
  • 521
  • 1
  • 7
  • 26
  • 2
    `mixing js and ajax`: AJAX is not a language, it's a way of retrieving a response from a server (e.g. from PHP code) with javascript, often used to generate content on the page based on user input. `$.get` is jQuery (which is a js lib) to perform a ajax `GET`request – online Thomas Dec 16 '16 at 08:34
  • 1
    @asdf_enel_hak Actually, the way the OP's using it, it's a global variable. You're right though; it should be declared before the if like `var Vorientation;` – qxz Dec 16 '16 at 08:36

2 Answers2

2

To run the function when your page is loading, you have to wrap code in $(document).ready(function(){ }); function.

Use this:

$(document).ready(function(){
    window.Vorientation=0;
    ratio();
    function ratio() {
        if(window.screen.width>window.screen.height)
        {
           Vorientation = 1;
        }
        else
        {
           Vorientation = 2;
        }
        $.get( "index.php", { orientation: Vorientation} )
           .done(function( data ) {
              alert( "Data Loaded: " + data );
           });
   }
});
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
2

You just need to add jQuery to your script and add your code in the document ready function https://learn.jquery.com/using-jquery-core/document-ready/

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
$(function() {
    ratio();
    function ratio() {
        var Vorientation;
        if(window.screen.width>window.screen.height) {
            Vorientation = 1;
        } else {
            Vorientation = 2;
        }
        $.get("index.php", { orientation: Vorientation})
            .done(function(data) {
                alert("Data Loaded: " + data);
            });
    }
});
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
EQuimper
  • 5,811
  • 8
  • 29
  • 42