Hello, I am trying two days now and I have spent about 12+ hours on this and I can't find a solution :( Please help, or I am gonna lose my mind!

I am trying to save user's monitor resolution on MySQL. I almost done it but, I have a problem with page reloads... I set a cookie that contains users resolution and I am trying to read it with php and then write it to MySQL, because javascript can't write to MySQL. The cookie is set OK, but php read it after a reload. Reload creates ton's of problem to other part's of web page, so can anyone please help me do exactly what I am doing without reload?

Here is my code:

<html>
<head>

<script type="text/javascript">
//setting cookie

function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
}

setCookie('res',screen.width+"x"+screen.height,365);

//cookie set
</script>

<?php
echo $screen_res = $_COOKIE["res"]; //here is the problem, this is null on first load
//I have to reload the page to get this work

//now connecting to mysql to write data
$dbhost = 'localhost';
$dbuser = 'username';
$dbname = 'test';
$dbpasswd = 'password';
$con = mysql_connect($dbhost, $dbuser, $dbpasswd);
unset($dbpasswd);
mysql_select_db("test", $con);

$sql = "CREATE TABLE test_table
(
Screen_res varchar(10)
)";
mysql_query($sql,$con);

mysql_query("INSERT INTO test_table (Screen_res)
VALUES ('$screen_res')");

mysql_close($con);
//data written
?>

</head>

<body onload="checkCookie()"> //<!-- I don't know what this does, but if I remove script brokes -->
</body>
</html>

Aslo, sorry for my bad english...

Dani AI

Generated

A clean, reliable way to avoid a page reload is to send the screen size to a tiny server endpoint asynchronously after the page loads. This moves the write into a separate request so PHP can record the value without waiting for a cookie on the initial response — which is the timing issue and were describing. The browser-side code posts the resolution; the server-side script stores it and returns a minimal response.

A minimal modern example (same-origin) — client sends JSON with fetch:

// client-side (runs after load)
(function () {
  var res = screen.width + 'x' + screen.height;
  fetch('/save_resolution.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ res: res })
  }).catch(function(){ /* silent fail for analytics */ });
})();

Server endpoint using PDO and a prepared statement:

<?php
// save_resolution.php
$data = json_decode(file_get_contents('php://input'), true);
$res = isset($data['res']) ? trim($data['res']) : null;
if (!preg_match('/^\d+x\d+$/', $res)) { http_response_code(400); exit; }

$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8mb4','dbuser','dbpass',[
  PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);

$stmt = $pdo->prepare('INSERT INTO screen_stats (screen_res, created_at) VALUES (:res, NOW())');
$stmt->execute([':res' => $res]);
http_response_code(204);

Notes, fallbacks and best practices:

  • For analytics on unload use navigator.sendBeacon with a small FormData; it avoids blocking and works well for pings. For ancient browsers, an image ping (new Image().src = '/save_resolution.php?res=...') is a tiny fallback.
  • Validate the value server-side (regex above). Use prepared statements (no string interpolation) and never CREATE TABLE on every request — create schema once and insert per hit.
  • For low traffic a direct INSERT is fine. For high traffic, buffer or queue writes (append-only log, cron batch import, or a message queue) to reduce DB contention.
  • Writing to a text file works for small volumes but needs locking and rotation; for scalability a DB or queuing layer is preferable.

This approach avoids reloads, keeps the main page flow intact, and addresses the timing problem observed by in the original code.

Recommended Answers

All 5 Replies

The problem is with the server waiting for PHP to finish its job before serving the page to the client. Your PHP code executes before your JS.

One easy solution is to call your script -which will be on a seperate file; not on the same as with your page- from JS, right after the cookie-job is finished.

Thanks a lot for your help :) I am not the super-advance-programmer and after a search I don't find a way doing it without AJAX (sadly I have no idea about AJAX programming). Is possible to call php from javascript without using AJAX;

Hello,

I believe that this is an old issue… the thing is that PHP run in server while JavaScript run in browser. There is no way to get JavaScript variables before the page appears in the browser (the first page anyone visit your web application – site) .

There are some workarounds to that … getting the variable and using instant redirection or to place what ever PHP was meant to do with view and use CSS innerHTML to produce it (or/and AJAX to get contents …. remember you can save resources keeping it in Asynchronous JavaScript and not XML)….

In generally speaking if this were a web application that I would like search engines to crawl I wouldn’t use all that. All the issues that arise of the acknowledgment of JavaScript variables (like screen resolution for example) the first time someone visit your site could overcome using CSS DHTML and Flash.

Thanks for the info. I am just creating a statistic aplicacion, it's not a big problem if some of the information are not 100% correct (e.g. someone fakes user agent). I think I found a solution, write the resolution to a text and then read it with php, but I don't know, isn't this gonna kill server's hdd or take time to write. Is this safe to do? Aslo, what you mean saying I am gonna have problem with search engineers;

That means search engines do not par well with AJAX. They may or may not be able to crawl your site.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.