Andre Chenier Andre Chenier - 6 months ago 17
Ajax Question

Assign Javascript Function Output to PHP session variable with native ajax [without JQuery & without user action (no click)]

my js knowledge is near to zero.

i want to


  1. get screen width in my index.php with js (no problem)

  2. assign js output value to a php session variable with ajax (?!?)

  3. add those values to database for future aims (no problem)



Also,


  • I don't want to use jquery library. (My only js usage will be at this
    point)

  • I don't want any button to click. (no visitor action)



what I tried is below. I created 2 pages:
index.php
and
dealviewportwidth.php


index.php will return viewport width, will done ajax part also and I will assign the value in dealviewportwidth.php by
$_GET
.

I fail, the session variable is not set. What to correct in // assignWidthToPHP part in index.php so the session variable will be set?

index.php ( return width by js, deal with ajax )

<script type="text/javascript">

function getViewportWidth()
{
var viewportwidth;

// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
if (typeof window.innerWidth != 'undefined')
{
viewportwidth = window.innerWidth
}

// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
else if (typeof document.documentElement != 'undefined'
&& typeof document.documentElement.clientWidth !=
'undefined' && document.documentElement.clientWidth != 0)
{
viewportwidth = document.documentElement.clientWidth
}

// older versions of IE
else
{
viewportwidth = document.getElementsByTagName('body')[0].clientWidth
}
return(viewportwidth);
}

// assignWidthToPHP
var xhttp = new XMLHttpRequest();
var width = getViewportWidth();
xhttp.open("GET", "http://localhost/dealviewportwidth.php?w="+width,false);
xhttp.send();

</script>


dealviewportwidth.php

<?php

session_start ();

$_SESSION["w"] = $_GET["w"];

var_dump($_SESSION["w"]);

?>

Answer

Your script is working on my computer, I just changed this line :

xhttp.open("GET", "http://localhost/dealviewportwidth.php?w="+width,false);

To

xhttp.open("GET", "/dealviewportwidth.php?w="+width,false);

Write a third script :

check.php

<?php

session_start();
echo $_SESSION["w"];

First open index.php, it will call dealviewportwidth.php in background Then open check.php it should display your data.

If you want to call dealviewportwidth.php directly from your browser, test if w parameter is set :

<?php

session_start();
if (isset($_GET["w"]))
{
    $_SESSION["w"] = $_GET["w"];
}   
var_dump($_SESSION["w"]);

?>