javascript unexpected token COOKIE - php

so i have this problem, i'm using a index.inc.php file to set a cookie and this is a must.
The problem of setting a cookie with server-side language is that it will not take effect on the first load. The javascript is on the template file index.tpl (Using XTemplate), the COOKIE2 and COOKIE3 are values defined on the PHP, they are cookie values, but on the first load, always empty.
var ligarei = getCookie('ligarei');
if(ligarei != "nao"){
var cookie2 = {COOKIE2};
var cookie3 = {COOKIE3};
var timeout = cookie3 - cookie2;
var timeout2 = 60 - timeout;
$(document).ready(function() {
if(timeout > 60){
popthat();
}
else if(timeout < 60){
setTimeout("popthat()", timeout2 * 1000);
}
});
}
The first getCookie function is ok, it doesn't matter if it's empty or null, but the problem is on the var cookie2 and cookie3, the result after compiled is:
var cookie = ;
And this is giving me a unexpected token error .
Any hints on how to solve this?
Thanks very much.

assuming your issue is because you cant in fact change the php code to conform with a simple empty check.
var ligarei = getCookie('ligarei');
if(ligarei != "nao"){
var cookie2 = {COOKIE2} + 0; // or + "" if it is a string
var cookie3 = {COOKIE3} + 0;
var timeout = cookie3 - cookie2;
var timeout2 = 60 - timeout;
$(document).ready(function() {
if(timeout > 60){
popthat();
}
else if(timeout < 60){
setTimeout("popthat()", timeout2 * 1000);
}
});
}

Use client side JS code to read the cookie.
In your $(document).ready function, you can read the cookies from the docmuent.cookies object. There is an example here regrading how to do that:
http://www.w3schools.com/js/js_cookies.asp
Also, there are some third-party js libs that simplify this task, e.g. cookie jar:
http://cookiejar.sourceforge.net/
If you work this way, you won't need to incorporate into your code the situation in which the cookie is not set (it is actually set, but not when your server-side code is running.

Cookies are always strings. I think that you are just missing the quotes:
var cookie2 = "{COOKIE2}";
var cookie3 = "{COOKIE3}";
Whatever, you are using one language (PHP) to generate source code for another language (JavaScript) so you just be very careful to obey the syntax rules of the target language. In PHP, a usual trick is to use json_encode() to output the values. E.g.:
<?php
$value = 'Foo "bar"; test';
echo json_encode($value);
... prints a ready to use JavaScript string, quotes and all:
"Foo \"bar\"; test"
Last but not least, it doesn't really matter whether you are using a server-side language to set the cookie, as this snippet illustrates:
<?php
setcookie('current-time', date('H:i:s'));
?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript">
window.onload = function(){
alert("Cookies: " + decodeURIComponent(document.cookie));
};
</script>
</head>
<body>
</body>
</html>

Related

Read Cookie Data from PHP in Javascript

I have a PHP file that contains both the PHP Code and the JQuery Code. My motive is to set cookies as and when the PHP code is executing and read the cookies set by PHP in the JQuery part of the code and make some decision. But I'm not able to do that. What would be the best way for me to achieve this.
I'm new to PHP any help would be great.
<?php>
if(isset($_POST['StartProcess'])){
$Process_step = 1;
setcookie("MyCookie", $Process_step); sleep(30);
$Process_step = 2;
setcookie("MyCookie", $Process_step); sleep(30);}
<?>
<html>
<head>
<script type="text/javascript">
$(document).ready(function(){
window.setInterval(function(){
var abc = document.cookie.split(";").map(function(el){ return el.split("="); }).reduce(function(prev,cur){ prev[cur[0]] = cur[1];return prev },{});
console.log(abc["MyCookie"]);
if(Step == 1){ do something;}else if(Step == 1){ do something else;}
})
})</script>
<head>
<body></body>
</html>
If I understand your question correctly, you would like to use PHP session value on the JQuery.
You can print the variable of PHP in the JQuery line. You can do it like this
var myvalue = "<?PHP $phpvarname ?>"
or you can use PHP session and assign it on the var.

Detect feature suport with modernizer and process with PHP based on result

So I need to detect webp support using modernizer, and then do some processign in PHP depending on the outcome of the result.
Now at first I thought I could set a cookie and get the cookie using PHP like so:
JS:
Modernizr.on('webp', function (result) {
if (result) {
setCookie("webpissupported", "yes", "365");
}
});
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
PHP:
$userAvatar = um_get_avatar_uri( um_profile('profile_photo'), 190 );
$patterns = array("/.jpg/", "/.jpeg/", "/.png/");
if (isset($_COOKIE['webpsupport']))
$userAvatar = preg_replace($patterns, "_result.webp", $userAvatar);
Now the problem with the above code is that I'm using the wordpress plugin w3 total cache, with the page cache enabled. this is causing the cookie to be cached and producing unexpected results.
So then I thought maybe I could do something like this:
<script type="text/javascript">
Modernizr.on("webp", function (result) {
if (result) {
<?php $webpSupport = true; ?>
}
});
</script>
But this will not work.
Anyone know how I might get around this problem.
You have mixed (client) browser-side processing with server-side (PHP). In your example, PHP block of code shall be executed regardless of what is to be processed later by browser/JS (or won't at all, in case of no JS browser). So, $webpSupport variable in this case and example shall be what you assign to it in order from top to bottom.
One way to achieve what you are after is to have JS cookie set, setCookie("webpissupported", "yes", "365"); and in the next page view read the $_COOKIE['webpissupported'] and serve images according to it.
Remember, webp is not a standard, although present in 72.85% browsers according to caniuse.com /StatCounter. You have to use it as progressive enhancement.

How to get variable from url for .js file?

Example: Suppose the current page url(window.location.href) is http://example.com/page.html
The html page source code is...
<html><head></head><body>
<script src="http://example.com/script.js?user=Ankit&ptid=18"></script>
</body></html>
Now I need to use 'src' variables in script.js
And the script file script.js should return
var a="Ankit"
var b="18"
Can we use something like echo $_GET like in php?
Found this here. If you're using jQuery, this should be helpful.
function getURLParameter(name) {
return decodeURI(
(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}
This is a javascript function that will return the value in the url of a parameter that you pass to it. In this case, you would call it with
var a = getURLParameter("user");
var b = getURLParameter("ptid");
EDIT: I misinterpreted the original version of your question as asking about getting parameters to the .html page being loaded. I just tested this solution, and it does not work within the .js file itself. However, if you declare your variables in the .js file, and place this in the onLoad event, removing var from in front of a and b, it should assign the variables correctly.
Maybe outdated but a nice piece of code and would exactly do what was asked for in OP
// Extract "GET" parameters from a JS include querystring
function getParams(script_name) {
// Find all script tags
var scripts = document.getElementsByTagName("script");
// Look through them trying to find ourselves
for(var i=0; i<scripts.length; i++) {
if(scripts[i].src.indexOf("/" + script_name) > -1) {
// Get an array of key=value strings of params
var pa = scripts[i].src.split("?").pop().split("&");
// Split each key=value into array, the construct js object
var p = {};
for(var j=0; j<pa.length; j++) {
var kv = pa[j].split("=");
p[kv[0]] = kv[1];
}
return p;
}
}
// No scripts match
return {};
}
Source: James Smith - Extract GET Params from a JavaScript Script Tag
I know it's an old post, but as I was looking for something like that I came across it. The very simple solution I finally adopted is the following one:
<html><head></head><body>
<script>
var a = "Ankit";
var b = 18;
</script>
<script src="http://example.com/script.js?user=Ankit&ptid=18"></script>
</body></html>
If you absolutely want to complicate your life and use Lahmizzar's solution, I would recommend to give an id to your tag script, which avoids a greedy function.
HTML :
<script src="http://example.com/script.js?user=Ankit&ptid=18" id="myScript"></script>
JS :
function getParams(script_id) {
var script = document.getElementById(script_id);
if(script) {
// Get an array of key=value strings of params
var pa = script.src.split("?").pop().split("&");
// Split each key=value into array, the construct js object
var p = {};
for(var j=0; j<pa.length; j++) {
var kv = pa[j].split("=");
p[kv[0]] = kv[1];
}
return p;
}
// No scripts match
return {};
}
getParams("myScript");

Calculate time passed variable to use in $.get()

I'm trying to update my database with some information. One of the key pieces of information is how much time has passed since the page first loaded and when the user click a button. My code looks like this:
<script>
function pauseVideo() {
$.get("video_pause.php?pause=" + timePassed + "&videoid=<?php echo $_GET['sessionid']; ?>&sessionid=<?php echo $_GET['videoid']; ?>");
}
</script>
and
<html>
<div id="pause" onclick="pauseVideo()">PAUSE</div>
</html>
My PHP is fine so ignore that. The part I'm having trouble with is the 'timePassed'. I need this to be the amount of time in seconds since the page was first loaded and the person clicks the PAUSE div.
I think I need to run a function on click to find the passed time and then use that time variable in the $.get() somehow?
When the document loads, just save the current time in a variable:
$(document).ready(function() {
var timeWhenLoaded = (new Date).getTime() / 1000;
});
Then, when the pause button is clicked, calculate the time that has passed:
function pauseVideo() {
var currTime = (new Date).getTime() / 1000;
// time in seconds
var timePassed = Math.floor(currTime - timeWhenLoaded);
$.get("video_pause.php?pause=" + timePassed + "&videoid=<?php echo $_GET['sessionid']; ?>&sessionid=<?php echo $_GET['videoid']; ?>");
}
Get rid of the onclick in your HTML, and remove your existing function, then put this in the head section of your page:
(function(){
var loadTime = (new Date).getTime(); // Page started loading
$(function(){
// DOM fully loaded, so move the assignment here if that is what
// you want to consider as the load time
$('#pause').click(function(){
$.get("video_pause.php?pause=" + Math.floor(((new Date).getTime() - loadTime)/1000) + "&videoid=<?php echo $_GET['sessionid']; ?>&sessionid=<?php echo $_GET['videoid']; ?>");
});
});
})();
Also note that you can never trust that variable on the server side. Anyone could input a negative number or even the word 'pizza' for the value if they really want to.
Something like:
var startTime = (new Date).getTime() / 1000;
function pauseVideo() {
var curTime = (new Date).getTime() / 1000;
var timePassed = Math.floor(curTime - startTime);
$.get("video_pause.php?pause=" + timePassed + "&videoid=<?php echo $_GET['sessionid']; ?>&sessionid=<?php echo $_GET['videoid']; ?>");
}
if the page with the following code is generated server-side, you can either just pass the current time to the script, as in:
<html>
<div id="pause" onclick="pauseVideo('" + curTime +"')">PAUSE</div>
</html>
(needs echo syntax)
or put it in a hidden field and pass it back to the server. (and do your calculations in php)
this way, you get the time passed since the page was requested...

Export javascript when the script is using PHP variables

I've got 800 lines of JS code inside a php script for a site, and littered throughout some of the JS functions are some PHP echos to insert variables from PHP. I want as much of the JS out of the page as possible, but I don't know any good way to do so, as I'm not very expirenced in JS, and since I didn't write the code I don't even know the reason for 100% of this stuff.
Here's an example of one of the worst offenders and one I have no idea how I'd convert out of the PHP page.
function validateCostCenter(el){
var objCB = el;
var emp_code = objCB.name.substring(23,29);
var local_plant_ID ="<?=$plant['Plant']['LocationID']?>";
var cc_plants_array = ["<?=$cc_plants?>"];
var CCPlant=false;
var CostCenterExists=false;
var std_cs_array = [];
<?
$idx = 0;
foreach($employees as $emp){
foreach($std_cs as $cs){
if($emp['Emp']['id'] == $cs[0]['emp_id']){
echo "std_cs_array[".$idx."] = [\"".trim($emp['Emp']['code'])."\",\"".$cs['0']['emp_id']."\",\"".$cs['0']['locationid']."\",\"".$cs['0']['charge_back_plant_id']."\"];\n";
$idx++;
}
}
}
?>
Would the best way to do this be to remove all the pure JS functions from the page and include them as an external file, and just leave the partly-php ones 100% as is? This is one of the most wasteful and slow pages we have on our site so I'd like it to be as optimized as possible, and separate java script files makes everything easier to debug.
Add all these php-generated variables as parameters of your function:
function validateCostCenter(el, local_plan_ID, cc_plants_array, std_cs_array)
BTW you could use json_encode to export your $employers array to javascript.
I will illustrate possible approaches on a very simple example.
Approach 1: Computation in PHP
The page.php contains the computation and the generated Javascript file (as you have it now):
<body>
<?php
function sum_php($a) {
$sum = 0;
for ($i = 0; $i < count($a); ++$i) $sum += $a[$i];
return $sum;
}
$a = array(1, 2, 3);
$sum = sum_php($a);
?>
<script type="text/javascript">
// JS generated by PHP:
alert("sum_php=" + <?php echo $sum ?>);
</script>
</body>
Approach 2: Computation in Javascript
The computation is moved out of PHP into a separate Javascript file page.js. PHP supplies the variables to the JS functions by JSON-encoding:
(1) page.php:
<head>
<script type="text/javascript" src="page.js"> </script>
</head>
<body>
<?php
$a = array(1, 2, 3);
?>
<script type="text/javascript">
sum_js(<?php echo json_encode($a) ?>); // supply $a to JS function
</script>
</body>
(2) page.js:
function sum_js(a) {
var s = 0;
for (var i = 0; i < a.length; ++i) s += a[i];
alert("sum_js=" + s);
return s;
}
Assumiong that these values are non-cacheable....
If it were me, I'd have a PHP create a global object/array to hold the values, and generate non-cacheable javascript file, then move the rest of the code into a static, cacheable file, e.g.
user_vars.php:
<?php
session_start();
....get values for variables....
print "user_vars={";
print " ' plant': " . json_encode($plant) . "\n";
print " ', cc_plants_array: [" . $cc_plants . "]\n";
....etc
generic.js:
function validateCostCenter(el){
var objCB = el;
var emp_code = objCB.name.substring(23,29);
var local_plant_ID = user_var.Plant.LocationID;
var cc_plants_array = user_var.cc_plants_array;
.....
However unpicking what the generated values for each parameter will be can be a bit tricky - the simplest approach might be to write a temporary file as PHP generates the base HTML rather than try to create the data structures twice.

Categories