-1

As I asked here I would like to know how I could pass the data from a simple JS function to php, and log it there.

I found this answer and tried to follow it. This is my code right now (both in the same file)

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"> </script>
</head>

<body>

    <script>
        function getClientScreenResolution() {
            var screenResolutionW = screen.width; 
            var screenResolutionH = screen.height;
            console.log(screenResolutionW + ' ' + screenResolutionH)
            $.post("index.php", {screenResolutionW: screenResolutionW, screenResolutionH: screenResolutionH})
        }
    </script>

    <script type="text/javascript">
        getScreenResolution();
    </script>

</body>
</html>
<?php

$screenResolutionW  = $_POST['screenResolutionW'];
$screenResolutionH  = $_POST['screenResolutionH'];

if(isset($_POST['screenResolutionW'])) {
   $fh = fopen('log.txt', 'a');     
   fwrite($fh, 'Screen res: '."".$screenResolutionW .'x'."".$screenResolutionH 
."\r\n");
   fclose($fh);
}
?>

However, this does not work. I wouldn't know how to fix this, whenever I try to google this problem people use more advanced methods, that I wouldn't even know how to start with.

Edit: My PHP and HMTL are in the same file (index.php). Edit 2: Removed old code for clarity.

This results in these error messages:

Notice: Undefined index: screenResolutionW in index.php on line 153

Notice: Undefined index: screenResolutionH in index.php on line 154
Buster
  • 446
  • 5
  • 16
  • In your PHP code you are extracting keys which never exist, so you need to send them in your JS code it like this `$.post("index.php", {screenResolutionW: screenResolutionW, screenResolutionH: screenResolutionH}` – Saadi Toumi Fouad May 01 '20 at 13:30
  • 1
    You have to learn som basics in a JSON-formatted string as @SaymoinSam provided in the $.post. – bestprogrammerintheworld May 01 '20 at 13:31
  • Why did you change the function? – Jay Blanchard May 01 '20 at 14:33
  • https://stackoverflow.com/a/61544141/12112111, I thought I should try it. I will change it back to your suggestion. – Buster May 01 '20 at 14:35
  • Check my edited answer now, where I show how to call the function. – Jay Blanchard May 01 '20 at 14:39
  • That makes sense, ofcourse I need to call the function. I added the script that calls for the function to be executed. However still nothing is being printed to the console, and it still logs only `Screen res: x`. I'll try to only use the code send here now as a seperate website, and see if it works then. – Buster May 01 '20 at 14:44
  • Mistake on my part, the seperate website does log the screen width and height to the console, however does not write it to log.txt. Edit: Main website now echo's the screen width and hight to console as well, however it isn't written to the PHP. – Buster May 01 '20 at 14:48
  • Look at the network tab in the browser's developer tools. When you load the page do you see the request? – Jay Blanchard May 01 '20 at 15:00
  • I see a lot of requests, like my fonts and CSS, but filtering JS I only see jquery.min.js and api.min.js. – Buster May 01 '20 at 15:12
  • You don't see a request to index.php? I just ran this code and It works for me. Are you doing this on a web server? – Jay Blanchard May 01 '20 at 15:13
  • Oh I'm sorry, yes I do see a request to index.php. – Buster May 01 '20 at 15:14
  • In that request do you see what is posted to the call? – Jay Blanchard May 01 '20 at 15:39

4 Answers4

3

What you want to do with $.post is include your data like this:

$.post("index.php", {screenResolutionW: screenResolutionW, screenResolutionH: screenResolutionH})

where the first of the pair is the POST identifier (the ['screenResolutionW']) and the second of the pair is the variable value.

You will also want to change your POST identifiers to be quoted:

$screenResolutionW  = $_POST['screenResolutionW'];
$screenResolutionH  = $_POST['screenResolutionH'];

Otherwise, you will get a warning about constants. I have also corrected the spelling in these variables, to reflect what you're trying to write into your file.

fwrite($fh, 'Screen res: '."".$screenResolutionW .'x'."".$screenResolutionH ."\r\n");

EDIT

Part of the problem is that you never call the function to execute it. Here is your HTML with the additions I have suggested, plus calling the function:

EDIT TWO

Added an onload handler for the document:

<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"> </script>
</head>

<body>

    <script>
        function getScreenResolution() {
            var screenResolutionW = screen.width; 
            var screenResolutionH = screen.height;
            console.log(screenResolutionW + ' ' + screenResolutionH);
            $.post("index.php", {screenResolutionW: screenResolutionW, screenResolutionH: screenResolutionH})
        }
    </script>

</body>
<script type="text/javascript">
    $(function() { 
        getScreenResolution();
    });
</script>
</html>

OTHER NOTES

You really should separate the PHP code and place it in a different file because when you run the page as it is now you should get one line logged that has no variables when the page initially runs, then one logged line when the JavaScript fires after the page loads.

Then once separated you should not run your PHP until you test for the existence of a variable, for example:

if(isset($_POST['screenResolutionW'])) {
    // your code to write to the file here
}

EDIT THREE

I placed all of the JavaScript in the same script block in the head of the file and have tested again:

<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"> </script>
    <script type="text/javascript">
    $(function() { 
        function getScreenResolution() {
            var screenResolutionW = screen.width; 
            var screenResolutionH = screen.height;
            console.log(screenResolutionW + ' ' + screenResolutionH);
            $.post("post_test.php", {screenResolutionW: screenResolutionW, screenResolutionH: screenResolutionH})
        }
        getScreenResolution();
    });
    </script>
</head>

<body>

</body>
</html>

Here you can see the variables are being posted: enter image description here

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/212944/discussion-on-answer-by-jay-blanchard-how-to-use-ajax-to-post-to-php). – Samuel Liew May 02 '20 at 00:59
1

Adapting the others answers.

try it:

function getScreenResolution() {
    "http://example.com/index.php", screenResolutionW + screenResolutionH
    $.ajax({
        url: '/index.php',
        method: 'POST',
        data: {
            screenResolutionW : screen.width,
            screenResolutionH : screen.height
        },
        success: function(data) { console.log(data); }
    });
}

And in your PHP

$screenResolutionW  = $_POST['screenResolutionW'];
$screenResolutionH  = $_POST['screenResolutionH'];

echo $screenResolutionW . " - " . $screenResolutionH;
Carlos
  • 142
  • 2
  • 10
0

you have to use serialize the array before doing post request.

        var screenResolutionW = screen.width; 
        var screenResolutionH = screen.height;
        var serializedArr = {
                    width: screenResolutionW,
                    height: screenResolutionH
                  };
        $.post('/index.php', serializedArr, function(response) {
            // Log the response to the console
            console.log("Response: "+response);
        });

In the server end, you will get values in $_POST variable.

jithu thomas
  • 279
  • 1
  • 3
-1

Apart of all those mistakes you have discovered thanks to other replies, you have these: $screenResoltuionW = ...

Notice you wrote "ltuion" and in the fopen command you have it correct. screenResolutionW

Same thing with $screenResoltuionH...

That's why you don't get any value in the file, because those variables doesn't exists.

HackeMate
  • 163
  • 7
  • 1
    We've already covered this. https://stackoverflow.com/questions/61543254/how-to-use-ajax-to-post-to-php/61543442?noredirect=1#comment108864758_61543442 – Jay Blanchard May 01 '20 at 14:16