简体   繁体   中英

viewport & screen width & height values to PHP via AJAX request

I want to get my viewport & screen width & height values to PHP. I found this link ( http://css-tricks.com/screen-resolution-notequalto-browser-window/ ) after quite much googleing.

I tried to apply it with the code below but my issue is I am not redirected to body.php after execution of index.html so I can't get any POST value from index.html to body.php . I am sure that jquery.js is loaded. I also tried the script in header part after jquery.js .

It seems that I couldn't achieve to make a proper request.

I know nothing about javascript or AJAX coding unfortunately. I don't want to use google analytics api.

I am using XAMPP for PHP execution.

Can you please kindly clarify where I am wrong with correctness suggestion? thanks all

My codes:

for index.html

<!DOCTYPE HTML>
<html>
    <head>      
        <meta charset=utf-8>
        <title>my title</title>

        <!-- latest jquery library -->
        <script src="js/jquery.js"></script>
    </head>

<body>
        <script>
            $.ajax({
              type: "POST",
              url: "http://localhost/public_html/body.php",
              data: {
                width        : $(window).width(),
                height       : $(window).height(),
                screen_width : screen.width,
                screen_height: screen.height
              }
            });
        </script>
</body>
</html>

for body.php

<?php
echo 'check print'.'<br />';

echo $_POST['width'].'<br />';
echo $_POST['height'].'<br />';
echo $_POST['screen_width'].'<br />';
echo $_POST['screen_height'].'<br />';
?>

you need to wait until the document is ready before trying to execute your script.

$(function(){

    $.ajax({
        url: 'http://localhost/public_html/body.php',
        type: 'POST',
        dataType: 'html',
        data: {
            width        : $(window).width(),
            height       : $(window).height(),
            screen_width : screen.width,
            screen_height: screen.height
        }
    })
    .done(function(response) {
        alert(response);
    })
    .fail(function(error) {
        alert(error);
    })
    .always(function() {
        console.log("complete");
    });

});

Check maybe console for ajax same origin error. My google version doens't allow ajax on localhost until forced explicitly.

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